<template>
  <div class="wms-app">
    <!-- 首页 - 供应商选择 -->
    <div v-if="currentView === 'suppliers'" class="supplier-list">
      <div class="header">
        <h1>拣货</h1>
        <!-- 隐藏配置检查按钮 -->
        <!--
        <button class="config-btn" @click="showConfig = !showConfig">
          {{ showConfig ? '隐藏配置' : '配置检查' }}
        </button>
        -->
      </div>
      
      <!-- 隐藏调试面板 -->
      <!--
      <div v-if="showConfig" class="debug-panel">
        <h3>调试面板</h3>
        <button @click="testApiConnection" class="test-btn" :disabled="testing">
          {{ testing ? '测试中...' : '测试API连接' }}
        </button>
        <button @click="findMissingFields" class="test-btn" :disabled="testing">
          查找缺失字段ID
        </button>
        <button @click="testSubmitWebhook" class="test-btn" :disabled="testing">
          测试提交拣货Webhook
        </button>
        <button @click="testPortalConfig" class="test-btn" :disabled="testing">
          测试外部门户配置
        </button>
        <button @click="testLocationStock" class="test-btn" :disabled="testing">
          测试库位库存数据
        </button>
        <button @click="testLocationStockAPI" class="test-btn" :disabled="testing">
          测试库位库存API配置
        </button>
        <button @click="testContainerConnection" class="test-btn" :disabled="testing">
          测试容器管理表连接
        </button>
        <div v-if="debugInfo" class="debug-info">
          <h4>调试信息:</h4>
          <pre>{{ debugInfo }}</pre>
        </div>
      </div>
      
      <!-- 配置检查面板 -->
      <ConfigCheck v-if="showConfig" />
      
      <!-- 加载状态 -->
      <div v-if="loading" class="loading">
        <p>正在加载供应商数据...</p>
      </div>
      
      <!-- 错误提示 -->
      <div v-if="error" class="error-message">
        <p>{{ error }}</p>
        <button @click="loadSuppliers" class="retry-btn">重试</button>
      </div>
      <div class="supplier-grid">
        <div 
          v-for="supplier in suppliers" 
          :key="supplier.id"
          class="supplier-card"
          @click="selectSupplier(supplier)"
        >
          <div class="supplier-name">{{ supplier.name }}</div>
          <div class="order-count">{{ supplier.orderCount }} 个拣货单</div>
        </div>
      </div>
    </div>

    <!-- 拣货单列表 -->
    <div v-if="currentView === 'orders'" class="order-list">
      <div class="header">
        <button class="back-btn" @click="backToSuppliers">← 返回</button>
        <h2>{{ selectedSupplier.name }} - 拣货单</h2>
        <div class="header-buttons">
          <button class="refresh-btn" @click="refreshPickingOrders" :disabled="loading">
            {{ loading ? '刷新中...' : '刷新' }}
          </button>
          <button class="filter-toggle-btn" @click="toggleFilterPanel">
            筛选 <span v-if="hasActiveFilters" class="filter-count">{{ getActiveFilterCount() }}</span>
          </button>
        </div>
      </div>
      
      <!-- 筛选面板 -->
      <div v-if="showFilterPanel" class="filter-panel">
        <div class="filter-row">
          <div class="filter-item">
            <label>发运目的地:</label>
            <select v-model="filters.shippingDestination" @change="applyFilters">
              <option value="">全部</option>
              <option v-for="dest in uniqueDestinations" :key="dest" :value="dest">
                {{ dest }}
              </option>
            </select>
          </div>
          <div class="filter-item">
            <label>出库单号:</label>
            <select v-model="filters.outboundPlanNumber" @change="applyFilters">
              <option value="">全部</option>
              <option v-for="plan in uniquePlanNumbers" :key="plan" :value="plan">
                {{ plan }}
              </option>
            </select>
          </div>
        </div>
        <div class="filter-row">
          <div class="filter-item">
            <label>拣货类型:</label>
            <select v-model="filters.pickingType" @change="applyFilters">
              <option value="">全部</option>
              <option v-for="type in uniquePickingTypes" :key="type" :value="type">
                {{ type }}
              </option>
            </select>
          </div>
          <div class="filter-item">
            <label>状态:</label>
            <select v-model="filters.status" @change="applyFilters">
              <option value="">全部</option>
              <option value="pending">待拣货</option>
              <option value="in_progress">拣货中</option>
              <option value="pending_confirm">待确认</option>
              <option value="cancelled">已取消</option>
            </select>
          </div>
        </div>
        <div class="filter-actions">
          <button class="clear-filters-btn" @click="clearFilters">清除筛选</button>
          <button class="close-filter-btn" @click="showFilterPanel = false">收起筛选</button>
        </div>
      </div>
      
      <div class="order-items">
        <div 
          v-for="order in filteredPickingOrders" 
          :key="order.id"
          class="order-item"
        >
          <div class="order-info">
            <div class="product-name">{{ order.productName }}</div>
            <div class="order-meta">
              <div class="meta-item">
                <span class="meta-label">发运目的地:</span>
                <span class="meta-value">{{ order.shippingDestination }}</span>
              </div>
              <div class="meta-item">
                <span class="meta-label">出库计划单号:</span>
                <span class="meta-value">{{ order.outboundPlanNumber }}</span>
              </div>
              <div class="meta-item">
                <span class="meta-label">拣货类型:</span>
                <span class="meta-value">{{ order.pickingType }}</span>
              </div>
              <div class="meta-item">
                <span class="meta-label">单据类型:</span>
                <span class="meta-value">{{ order.documentType }}</span>
              </div>
              <div class="meta-item">
                <span class="meta-label">状态:</span>
                <span class="meta-value status" :class="getStatusClass(order.status)">{{ getStatusText(order.status) }}</span>
              </div>
              <div class="meta-item" v-if="order.containerCode">
                <span class="meta-label">绑定容器:</span>
                <span class="meta-value container-code">{{ order.containerCode }}</span>
              </div>
              <div class="meta-item container-warning" v-else>
                <span class="meta-label">绑定容器:</span>
                <span class="meta-value no-container">未绑定容器</span>
              </div>
            </div>
            <div class="quantity-info">
              <span>应拣: {{ order.requiredQuantity || 0 }}</span>
              <span>已拣: {{ order.pickedQuantity || 0 }}</span>
              <span>剩余: {{ getRemainingQuantity(order) }}</span>
            </div>
          </div>
          <div class="order-actions">
            <button 
              class="pick-btn" 
              @click="startPicking(order)"
              :disabled="order.status === 'completed' || order.status === 'pending_confirm' || (!order.containerCode || order.containerCode.trim() === '')"
              :class="{ 'no-container': !order.containerCode || order.containerCode.trim() === '' }"
              v-if="order.status !== 'pending_confirm'"
              :title="getPickingButtonTitle(order)"
            >
              去拣货
            </button>
            <button 
              class="complete-btn" 
              :class="{ 'container-bound': order.status === 'container_bound' }"
              @click="completePicking(order)"
              :disabled="order.status === 'completed' || order.status === 'container_bound'"
              v-if="order.status !== 'pending_confirm'"
              :data-order-status="order.status"
              :data-container-code="order.containerCode || 'none'"
              :title="`订单状态: ${order.status}, 容器码: ${order.containerCode || '未绑定'}`"
            >
              {{ order.status === 'container_bound' ? '已绑定容器' : '绑定容器' }}
            </button>
            <!-- 待确认状态的操作按钮 -->
            <button 
              class="confirm-btn" 
              @click="confirmOrder(order)"
              v-if="order.status === 'pending_confirm'"
            >
              确认拣货
            </button>
          </div>
        </div>
      </div>
    </div>

    <!-- 拣货详情 -->
    <div v-if="currentView === 'picking'" class="picking-detail">
      <div class="header">
        <button class="back-btn" @click="backToOrders">← 返回</button>
        <h2>拣货详情</h2>
      </div>
      
      <div class="product-info">
        <div class="info-item">
          <label>商品名称:</label>
          <span>{{ currentOrder.productName }}</span>
        </div>
        <div class="info-item">
          <label>商品条码:</label>
          <span>{{ currentOrder.barcode || '暂无条码信息' }}</span>
        </div>
        <div class="info-item">
          <label>生产日期:</label>
          <span>{{ currentOrder.productionDate || '暂无生产日期' }}</span>
        </div>
        <div class="info-item">
          <label>剩余拣货数量:</label>
          <span>{{ getRemainingQuantity(currentOrder) }}</span>
        </div>
      </div>

      <div class="location-info">
        <div class="location-item">
          <label>选择库位:</label>
          <select 
            v-model="selectedLocation" 
            @change="handleLocationChange"
            class="location-select"
            :disabled="loadingLocations"
            v-if="availableLocations.length > 1"
          >
            <option value="">{{ loadingLocations ? '加载中...' : '请选择库位' }}</option>
            <option 
              v-for="location in availableLocations" 
              :key="location.id"
              :value="location"
              :disabled="getDisplayLocationStock(location) <= 0"
            >
              {{ location.locationCode }} (当前库存: {{ getDisplayLocationStock(location) }}, 生产日期: {{ location.productionDate || '无' }})
              {{ getDisplayLocationStock(location) <= 0 ? ' [库存不足]' : '' }}
            </option>
          </select>
          <div v-else-if="availableLocations.length === 1" class="single-location" 
               :class="{ 'stock-insufficient': getDisplayLocationStock(availableLocations[0]) <= 0 }">
            {{ availableLocations[0].locationCode }} 
            (当前库存: {{ getDisplayLocationStock(availableLocations[0]) }}, 生产日期: {{ availableLocations[0].productionDate || '无' }})
            <span v-if="getDisplayLocationStock(availableLocations[0]) <= 0" class="stock-warning"> [库存不足]</span>
          </div>
          <div v-else-if="!loadingLocations" class="no-location">
            暂无可用库位
          </div>
          <div v-else class="loading-location">
            加载库位中...
          </div>
        </div>
        <div class="location-item" v-if="selectedLocation">
          <label>当前库存:</label>
          <span>{{ getDisplayLocationStock(selectedLocation) }}</span>
        </div>
      </div>

      <div class="pick-form">
        <!-- 新增验证输入框 -->
        <div class="form-group">
          <label for="inputLocationCode">拣货库位:</label>
          <input 
            id="inputLocationCode"
            v-model="inputLocationCode" 
            type="text" 
            placeholder="请扫描或输入库位编码"
            @input="validateLocationCode"
            :class="{ 'error': locationValidationError }"
          >
          <div v-if="locationValidationError" class="error-message">
            {{ locationValidationError }}
          </div>
        </div>
        
        <div class="form-group">
          <label for="inputBarcode">拣货商品条码:</label>
          <input 
            id="inputBarcode"
            v-model="inputBarcode" 
            type="text" 
            placeholder="请扫描或输入商品条码"
            @input="validateBarcode"
            :class="{ 'error': barcodeValidationError }"
          >
          <div v-if="barcodeValidationError" class="error-message">
            {{ barcodeValidationError }}
          </div>
        </div>
        
        <div class="form-group">
          <label for="pickQuantity">拣货数量:</label>
          <input 
            id="pickQuantity"
            v-model="pickQuantity" 
            type="number" 
            placeholder="请输入拣货数量"
            min="1"
            @input="validatePickQuantity"
            :class="{ 'error': quantityError }"
          >
          <div v-if="selectedLocation" class="quantity-info">
            <span class="limit-info">最大可拣: {{ getMaxPickQuantity() }} 件</span>
            <span class="breakdown">
              (剩余: {{ currentOrder.remainingQuantity }}, 
              库存: {{ getDisplayLocationStock(selectedLocation) }})
            </span>
          </div>
          <div v-if="quantityError" class="error-message">
            {{ quantityError }}
          </div>
          
          <!-- 操作状态提示 -->
          <div v-if="pickingOperationState.isSubmitting" class="operation-status">
            <span class="status-icon">⏳</span>
            正在提交拣货操作，请稍等...
          </div>
        </div>
        <button 
          class="submit-btn" 
          @click="showSubmitConfirm"
          :disabled="!canSubmitPicking"
        >
          {{ getSubmitButtonText() }}
        </button>
        
        <!-- 调试按钮 - 隐藏 -->
        <div class="debug-buttons" style="display: none;">
          <button class="debug-btn" @click="debugLocationStock" :disabled="testing">
            调试库位数据
          </button>
          <button class="debug-btn" @click="reloadLocationStock" :disabled="loadingLocations">
            重新加载库位
          </button>
        </div>
        
        <!-- 调试信息显示 -->
        <div v-if="locationDebugInfo" class="location-debug-info">
          <h4>库位调试信息:</h4>
          <pre>{{ locationDebugInfo }}</pre>
        </div>
      </div>
    </div>

    <!-- 二次确认弹窗 -->
    <div v-if="showConfirmModal" class="modal-overlay" @click="closeModal">
      <div class="modal-content" @click.stop>
        <h3>{{ confirmTitle }}</h3>
        <p>{{ confirmMessage }}</p>
        <div class="modal-actions">
          <button class="cancel-btn" @click="closeModal">取消</button>
          <button class="confirm-btn" @click="confirmAction">确认</button>
        </div>
      </div>
    </div>

    <!-- 容器选择弹窗 -->
    <div v-if="showContainerModal" class="modal-overlay" @click="closeContainerModal">
      <div class="container-modal-content" @click.stop>
        <h3>选择绑定容器</h3>
        <p v-if="currentOrder">为拣货单：{{ currentOrder.productName }} 选择容器</p>
        
        <!-- 加载状态 -->
        <div v-if="loadingContainers" class="loading-containers">
          <p>正在加载可用容器...</p>
        </div>
        
        <!-- 无容器提示 -->
        <div v-else-if="availableContainers.length === 0" class="no-containers">
          <p>暂无可用容器</p>
        </div>
        
        <!-- 搜索栏 -->
        <div v-if="!loadingContainers && availableContainers.length > 0" class="container-search">
          <input
            v-model="containerSearchQuery"
            type="text"
            placeholder="输入容器码进行搜索..."
            class="search-input"
          />
          <div class="search-info" v-if="containerSearchQuery.trim()">
            找到 {{ filteredContainers.length }} 个匹配的容器
          </div>
          <div class="search-hint" v-else>
            请输入容器码进行搜索
          </div>
        </div>
        
        <!-- 容器列表 -->
        <div v-if="!loadingContainers && containerSearchQuery.trim() && filteredContainers.length > 0" class="container-list">
          <div 
            v-for="container in filteredContainers" 
            :key="container.id"
            class="container-item"
            :class="{ 'selected': selectedContainer?.id === container.id }"
            @click="selectContainer(container)"
          >
            <div class="container-info">
              <div class="container-code">{{ container.containerCode }}</div>
              <div class="container-details">
                <span class="container-status">状态：{{ container.status || '可用' }}</span>
                <span class="container-station" v-if="container.deliveryStation">
                  配送站点：{{ container.deliveryStation }}
                </span>
                <span class="container-station empty" v-else>
                  配送站点：通用
                </span>
              </div>
            </div>
          </div>
        </div>
        
        <!-- 搜索无结果提示 -->
        <div v-if="!loadingContainers && containerSearchQuery.trim() && filteredContainers.length === 0" class="no-search-results">
          <p>未找到匹配的容器</p>
          <p class="search-suggestion">请尝试其他关键词</p>
        </div>
        
        <div class="modal-actions">
          <button class="cancel-btn" @click="closeContainerModal">取消</button>
          <button 
            class="confirm-btn" 
            @click="confirmContainerBinding"
            :disabled="!selectedContainer"
          >
            确认绑定
          </button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from "vue";
import wmsApi from "./api/index.js";
import ConfigCheck from "./components/ConfigCheck.vue";

// 获取明道云外部门户配置对象
let config = null;
try {
  // 从全局对象获取明道云配置
  config = window.config || window.mdAppConfig || {};
  console.log('明道云配置对象:', config);
} catch (error) {
  console.error('获取明道云配置失败:', error);
}

const currentView = ref('suppliers')
const suppliers = ref([])
const selectedSupplier = ref(null)
const pickingOrders = ref([])
const currentOrder = ref(null)
const pickQuantity = ref('')
const quantityError = ref('') // 添加数量验证错误信息
// 新增验证字段
const inputLocationCode = ref('') // 拣货库位输入
const inputBarcode = ref('') // 拣货商品条码输入
const locationValidationError = ref('') // 库位验证错误信息
const barcodeValidationError = ref('') // 条码验证错误信息
const showConfirmModal = ref(false)
const confirmTitle = ref('')
const confirmMessage = ref('')
const confirmType = ref('')
const showConfig = ref(false)

// 容器绑定相关状态
const showContainerModal = ref(false)
const availableContainers = ref([])
const selectedContainer = ref(null)
const loadingContainers = ref(false)
const containerSearchQuery = ref('')

// 筛选相关状态
const showFilterPanel = ref(false)
const filters = ref({
  shippingDestination: '',
  outboundPlanNumber: '',
  pickingType: '',
  status: ''
})
const loading = ref(false)
const error = ref('')
const testing = ref(false)
const debugInfo = ref('')
const loadingLocations = ref(false)
const availableLocations = ref([])
const selectedLocation = ref(null)
const locationDebugInfo = ref('')

// 计划出库数量管理系统
const plannedOutboundQuantities = ref(new Map()) // 存储每个订单的初始计划出库数量

// 前端库存管理系统 - 用于解决多次拣货时库存数量不准确的问题
const locationStockCache = ref(new Map()) // 存储库位的前端库存数量 key: locationId, value: currentStock

// 拣货操作状态管理 - 防止快速重复操作
const pickingOperationState = ref({
  isSubmitting: false,           // 是否正在提交拣货
  lastOperationTime: 0,          // 上次操作时间戳
  operationCooldown: 1000,       // 操作冷却时间（1秒）
  locationOperations: new Map(), // 库位操作记录 key: locationId, value: { count, lastTime }
  transactionId: null           // 当前事务ID，用于去重
})

// 待处理的拣货操作队列 - 确保操作顺序执行
const pickingQueue = ref([])
const isProcessingQueue = ref(false)

// 计算属性：验证是否可以提交拣货
const canSubmitPicking = computed(() => {
  // 必须选择了库位
  if (!selectedLocation.value) {
    return false
  }
  
  // 必须输入了库位编码并且验证通过
  if (!inputLocationCode.value.trim() || locationValidationError.value) {
    return false
  }
  
  // 必须输入了商品条码并且验证通过
  if (!inputBarcode.value.trim() || barcodeValidationError.value) {
    return false
  }
  
  // 必须输入了拣货数量并且验证通过
  if (!pickQuantity.value || pickQuantity.value <= 0 || quantityError.value) {
    return false
  }
  
  // 库存必须足够
  if (selectedLocation.value && getDisplayLocationStock(selectedLocation.value) <= 0) {
    return false
  }
  
  // 不能正在提交中
  if (pickingOperationState.value.isSubmitting) {
    return false
  }
  
  return true
})

// 计算属性：过滤后的容器列表
const filteredContainers = computed(() => {
  // 只有在有搜索条件时才显示容器
  if (!containerSearchQuery.value.trim()) {
    return [] // 默认不显示任何容器
  }
  
  const query = containerSearchQuery.value.trim().toLowerCase()
  return availableContainers.value.filter(container => {
    return container.containerCode && container.containerCode.toLowerCase().includes(query)
  })
})

// 计算属性：过滤后的拣货单
const filteredPickingOrders = computed(() => {
  if (!pickingOrders.value || pickingOrders.value.length === 0) {
    return []
  }
  
  return pickingOrders.value.filter(order => {
    // 注释掉排除已完成单据的逻辑，允许显示已绑定容器的订单
    // if (isOrderCompleted(order)) {
    //   return false
    // }
    
    // 发运目的地筛选
    if (filters.value.shippingDestination && 
        order.shippingDestination !== filters.value.shippingDestination) {
      return false
    }
    
    // 出库单号筛选
    if (filters.value.outboundPlanNumber && 
        order.outboundPlanNumber !== filters.value.outboundPlanNumber) {
      return false
    }
    
    // 拣货类型筛选
    if (filters.value.pickingType && 
        order.pickingType !== filters.value.pickingType) {
      return false
    }
    
    // 状态筛选
    if (filters.value.status && 
        order.status !== filters.value.status) {
      return false
    }
    
    return true
  })
})

// 计算属性：获取唯一的发运目的地列表（排除已完成的单据）
const uniqueDestinations = computed(() => {
  if (!pickingOrders.value) return []
  const activeOrders = pickingOrders.value.filter(order => !isOrderCompleted(order))
  const destinations = [...new Set(activeOrders.map(order => order.shippingDestination))]
  return destinations.filter(dest => dest && dest.trim())
})

// 计算属性：获取唯一的出库单号列表（排除已完成的单据）
const uniquePlanNumbers = computed(() => {
  if (!pickingOrders.value) return []
  const activeOrders = pickingOrders.value.filter(order => !isOrderCompleted(order))
  const planNumbers = [...new Set(activeOrders.map(order => order.outboundPlanNumber))]
  return planNumbers.filter(plan => plan && plan.trim())
})

// 计算属性：获取唯一的拣货类型列表（排除已完成的单据）
const uniquePickingTypes = computed(() => {
  if (!pickingOrders.value) return []
  const activeOrders = pickingOrders.value.filter(order => !isOrderCompleted(order))
  const types = [...new Set(activeOrders.map(order => order.pickingType))]
  return types.filter(type => type && type.trim())
})

// 计算属性：检查是否有激活的筛选条件
const hasActiveFilters = computed(() => {
  return filters.value.shippingDestination || 
         filters.value.outboundPlanNumber || 
         filters.value.pickingType || 
         filters.value.status
})

// 测试API连接
async function testApiConnection() {
  testing.value = true
  debugInfo.value = ''
  
  try {
    console.log('开始API连接测试...')
    
    // 验证配置
    const configValidation = wmsApi.validateConfiguration()
    console.log('配置验证结果:', configValidation)
    
    // 测试连接
    const connectionResult = await wmsApi.testConnection()
    console.log('连接测试结果:', connectionResult)
    
    // 显示调试信息
    const debugData = {
      配置验证: configValidation,
      连接测试: connectionResult,
      时间: new Date().toLocaleString()
    }
    
    debugInfo.value = JSON.stringify(debugData, null, 2)
    
  } catch (error) {
    console.error('API测试失败:', error)
    debugInfo.value = `测试失败: ${error.message}\n\n完整错误信息:\n${JSON.stringify(error, null, 2)}`
  } finally {
    testing.value = false
  }
}

// 查找缺失的字段ID
async function findMissingFields() {
  testing.value = true
  debugInfo.value = ''
  
  try {
    console.log('开始查找缺失字段ID...')
    
    // 获取一条数据来分析字段结构
    const result = await wmsApi.getAllPickingOrders()
    
    if (result && result.rows && result.rows.length > 0) {
      const firstRow = result.rows[0].rawData // 获取原始数据
      
      const fieldAnalysis = {
        '总字段数': Object.keys(firstRow).length,
        '可能的条码字段': [],
        '可能的日期字段': [],
        '所有非空字段': []
      }
      
      // 分析每个字段
      Object.keys(firstRow).forEach(key => {
        const value = firstRow[key]
        if (value && value !== '' && value !== null && value !== undefined) {
          fieldAnalysis['所有非空字段'].push({
            ID: key,
            值: String(value).substring(0, 50), // 限制显示长度
            类型: typeof value
          })
          
          if (typeof value === 'string') {
            // 查找可能的条码字段
            if (value.match(/^\d{8,20}$/)) {
              fieldAnalysis['可能的条码字段'].push({
                ID: key,
                值: value
              })
            }
            
            // 查找可能的日期字段
            if (value.match(/^\d{4}[-\/]\d{1,2}[-\/]\d{1,2}/) || 
                value.includes('2024') || value.includes('2023') || value.includes('2025')) {
              fieldAnalysis['可能的日期字段'].push({
                ID: key,
                值: value
              })
            }
          }
        }
      })
      
      debugInfo.value = JSON.stringify(fieldAnalysis, null, 2)
      
    } else {
      debugInfo.value = '未找到数据进行字段分析'
    }
    
  } catch (error) {
    console.error('字段分析失败:', error)
    debugInfo.value = `字段分析失败: ${error.message}`
  } finally {
    testing.value = false
  }
}

// 测试提交拣货webhook
async function testSubmitWebhook() {
  testing.value = true
  debugInfo.value = ''
  
  try {
    console.log('开始测试提交拣货webhook...')
    
    const result = await wmsApi.testSubmitWebhook()
    
    debugInfo.value = JSON.stringify({
      测试类型: '提交拣货Webhook测试',
      结果: result,
      时间: new Date().toLocaleString(),
      webhook地址: '(通过参数配置 submitWebhookURL)'
    }, null, 2)
    
  } catch (error) {
    console.error('提交拣货webhook测试失败:', error)
    debugInfo.value = `测试失败: ${error.message}`
  } finally {
    testing.value = false
  }
}

// 测试外部门户配置
async function testPortalConfig() {
  testing.value = true
  debugInfo.value = ''
  
  try {
    console.log('开始测试外部门户配置...')
    
    // 测试获取外部门户用户信息
    const userInfo = await wmsApi.getCurrentUserInfo()
    
    // 获取原始config对象进行对比
    const rawConfig = window.config || window.mdAppConfig || {};
    
    const configTest = {
      '外部门户配置存在': !!rawConfig,
      '当前账户信息存在': !!(rawConfig && rawConfig.currentAccount),
      '原始config对象': rawConfig,
      '解析的用户信息': userInfo,
      '手机号获取': userInfo.phone,
      '姓名获取': userInfo.name,
      '用户ID获取': userInfo.userId,
      'config.currentAccount详情': rawConfig.currentAccount || '不存在',
      '测试时间': new Date().toLocaleString()
    }
    
    debugInfo.value = JSON.stringify(configTest, null, 2)
    
  } catch (error) {
    console.error('外部门户配置测试失败:', error)
    debugInfo.value = `测试失败: ${error.message}`
  } finally {
    testing.value = false
  }
}

// 测试库位库存API配置
async function testLocationStockAPI() {
  testing.value = true
  debugInfo.value = ''
  
  try {
    console.log('开始测试库位库存API配置...')
    
    const result = await wmsApi.testLocationStockAPI()
    
    debugInfo.value = JSON.stringify({
      测试类型: '库位库存API配置测试',
      结果: result,
      时间: new Date().toLocaleString()
    }, null, 2)
    
  } catch (error) {
    console.error('库位库存API配置测试失败:', error)
    debugInfo.value = `测试失败: ${error.message}`
  } finally {
    testing.value = false
  }
}

// 测试库位库存数据
async function testLocationStock() {
  testing.value = true
  debugInfo.value = ''
  
  try {
    console.log('开始测试库位库存数据...')
    
    // 先尝试获取一些拣货单数据作为测试参数
    const pickingOrdersResult = await wmsApi.getAllPickingOrders()
    
    let testResult = {
      测试时间: new Date().toLocaleString(),
      库位库存字段配置: {
        商品名称字段: LOCATION_STOCK_FIELDS.PRODUCT_NAME || '(未配置)',
        供应商名称字段: LOCATION_STOCK_FIELDS.SUPPLIER_NAME || '(未配置)', 
        生产日期字段: LOCATION_STOCK_FIELDS.PRODUCTION_DATE || '(未配置)',
        锁定库存字段: LOCATION_STOCK_FIELDS.LOCKED_STOCK || '(未配置)'
      }
    }
    
    if (pickingOrdersResult && pickingOrdersResult.rows && pickingOrdersResult.rows.length > 0) {
      const firstOrder = pickingOrdersResult.rows[0]
      testResult.测试拣货单数据 = {
        商品名称: firstOrder.productName,
        供应商名称: firstOrder.supplierName,
        生产日期: firstOrder.productionDate
      }
      
      // 使用第一个拣货单的数据测试库位库存查询
      const locationResult = await wmsApi.getLocationStock(
        firstOrder.productName,
        firstOrder.supplierName,
        firstOrder.productionDate,
        firstOrder.pickingType
      )
      
      testResult.库位库存查询结果 = {
        找到库位数量: locationResult?.rows?.length || 0,
        库位数据样本: locationResult?.rows?.slice(0, 2) || []
      }
      
      // 如果找到库位数据，分析字段结构
      if (locationResult?.rows?.length > 0) {
        const firstLocation = locationResult.rows[0]
        testResult.库位数据字段分析 = {
          原始数据字段: Object.keys(firstLocation.rawData || {}),
          转换后字段: Object.keys(firstLocation)
        }
      }
    } else {
      testResult.错误 = '没有找到拣货单数据用于测试'
    }
    
    debugInfo.value = JSON.stringify(testResult, null, 2)
    
  } catch (error) {
    console.error('库位库存数据测试失败:', error)
    debugInfo.value = `测试失败: ${error.message}`
  } finally {
    testing.value = false
  }
}

// 调试库位数据
async function debugLocationStock() {
  if (!currentOrder.value) {
    locationDebugInfo.value = '错误：当前拣货单信息不存在'
    return
  }
  
  testing.value = true
  locationDebugInfo.value = ''
  
  try {
    console.log('开始调试库位数据...')
    
    const debugData = {
      调试时间: new Date().toLocaleString(),
      当前拣货单信息: {
        商品名称: currentOrder.value.productName,
        供应商名称: currentOrder.value.supplierName,
        生产日期: currentOrder.value.productionDate,
        批次码: currentOrder.value.batchCode
      },
      库位库存字段配置: {
        商品名称字段ID: LOCATION_STOCK_FIELDS.PRODUCT_NAME || '(未配置)',
        供应商名称字段ID: LOCATION_STOCK_FIELDS.SUPPLIER_NAME || '(未配置)',
        生产日期字段ID: LOCATION_STOCK_FIELDS.PRODUCTION_DATE || '(未配置)',
        锁定库存字段ID: LOCATION_STOCK_FIELDS.LOCKED_STOCK || '(未配置)',
        库位编码字段ID: '(未配置)'
      }
    }
    
    // 调用库位库存API
    try {
      const result = await wmsApi.getLocationStock(
        currentOrder.value.productName,
        currentOrder.value.supplierName,
        currentOrder.value.productionDate,
        currentOrder.value.pickingType
      )
      
      debugData.API调用结果 = {
        成功: true,
        返回数据结构: result ? Object.keys(result) : '无数据',
        库位数量: result?.rows?.length || 0
      }
      
      if (result?.rows && result.rows.length > 0) {
        debugData.库位数据样本 = result.rows.slice(0, 3).map(location => ({
          库位ID: location.id,
          库位编码: location.locationCode,
          商品名称: location.productName,
          供应商名称: location.supplierName,
          生产日期: location.productionDate,
          锁定库存: location.lockedStock,
          原始数据字段: location.rawData ? Object.keys(location.rawData) : '无原始数据'
        }))
        
        // 检查第一个库位的原始数据
        if (result.rows[0]?.rawData) {
          debugData.原始库位数据分析 = {
            全部字段: Object.keys(result.rows[0].rawData),
            字段值样本: {}
          }
          
          // 显示前10个字段的值
          const fields = Object.keys(result.rows[0].rawData).slice(0, 10)
          fields.forEach(field => {
            const value = result.rows[0].rawData[field]
            debugData.原始库位数据分析.字段值样本[field] = typeof value === 'string' ? value.substring(0, 50) : value
          })
        }
      } else {
        debugData.无库位数据原因分析 = {
          可能原因1: '筛选条件过于严格，找不到匹配的库位',
          可能原因2: '库位库存表中没有相关数据',
          可能原因3: '字段ID配置错误',
          可能原因4: '库位编码字段未配置，无法正确显示库位信息'
        }
      }
      
    } catch (apiError) {
      debugData.API调用结果 = {
        成功: false,
        错误信息: apiError.message,
        错误类型: apiError.name
      }
    }
    
    locationDebugInfo.value = JSON.stringify(debugData, null, 2)
    
  } catch (error) {
    console.error('调试库位数据失败:', error)
    locationDebugInfo.value = `调试失败: ${error.message}`
  } finally {
    testing.value = false
  }
}

// 重新加载库位数据
async function reloadLocationStock() {
  if (!currentOrder.value) {
    alert('当前拣货单信息不存在')
    return
  }
  
  console.log('重新加载库位数据...')
  await loadAvailableLocations(
    currentOrder.value.productName,
    currentOrder.value.supplierName,
    currentOrder.value.productionDate
  )
  
  locationDebugInfo.value = `重新加载完成，找到 ${availableLocations.value.length} 个库位`
}

// 测试容器管理表连接
async function testContainerConnection() {
  testing.value = true
  debugInfo.value = ''
  
  try {
    console.log('开始测试容器管理表连接...')
    
    const result = await wmsApi.testContainerConnection()
    
    debugInfo.value = JSON.stringify({
      测试类型: '容器管理表连接测试',
      结果: result,
      时间: new Date().toLocaleString()
    }, null, 2)
    
  } catch (error) {
    console.error('容器管理表连接测试失败:', error)
    debugInfo.value = `测试失败: ${error.message}`
  } finally {
    testing.value = false
  }
}

onMounted(() => {
  // 页面加载时输出外部门户配置信息
  console.log('页面加载 - 外部门户配置:', config);
  loadSuppliers()
})

async function loadSuppliers() {
  if (loading.value) return // 防止重复加载
  
  loading.value = true
  error.value = ''
  
  try {
    console.log('开始加载供应商数据...')
    // 获取所有拣货单数据
    const result = await wmsApi.getSuppliers() // 实际上是获取拣货单数据
    console.log('API返回数据:', result?.rows?.length, '条记录')
    
    if (result && result.rows && result.rows.length > 0) {
      // 清空之前的数据，避免重复
      suppliers.value = []
      
      // 从拣货单数据中提取供应商信息并统计
      const supplierMap = new Map()
      
      result.rows.forEach(orderData => {
        // 跳过已完成的拣货单
        if (isOrderCompleted(orderData)) {
          return; // 不计入供应商统计
        }
        
        // 现在orderData已经是转换后的格式，直接使用supplierName字段
        const supplierName = orderData.supplierName || '未知供应商'
        
        // 如果供应商已存在，增加拣货单数量；否则创建新供应商
        if (supplierMap.has(supplierName)) {
          const existing = supplierMap.get(supplierName)
          existing.orderCount += 1
          existing.orders.push(orderData)
        } else {
          supplierMap.set(supplierName, {
            id: supplierName, // 使用供应商名称作为ID
            name: supplierName,
            orderCount: 1,
            orders: [orderData] // 存储该供应商的所有拣货单
          })
        }
      })
      
      // 将Map转换为数组，并过滤掉没有未完成订单的供应商
      suppliers.value = Array.from(supplierMap.values()).filter(supplier => supplier.orderCount > 0)
      
      // 初始化所有未完成订单的计划出库数量
      result.rows.forEach(orderData => {
        if (!isOrderCompleted(orderData)) {
          initializePlannedQuantity(orderData.id, orderData)
        }
      })
      
      const totalOrders = result.rows.length
      const completedOrders = result.rows.filter(order => isOrderCompleted(order)).length
      const activeOrders = totalOrders - completedOrders
      
      console.log(`订单统计 - 总计: ${totalOrders}, 已完成: ${completedOrders}, 未完成: ${activeOrders}`)
      console.log('处理后的供应商数据:', suppliers.value)
      console.log('初始化的计划出库数量:', Array.from(plannedOutboundQuantities.value.entries()))
      
    } else {
      suppliers.value = []
      error.value = '未获取到拣货单数据'
    }
  } catch (err) {
    console.error('加载供应商失败:', err)
    error.value = `加载失败: ${err.message}`
    suppliers.value = []
  } finally {
    loading.value = false
  }
}

function selectSupplier(supplier) {
  selectedSupplier.value = supplier
  currentView.value = 'orders'
  // 清除之前的筛选条件
  clearFilters()
  showFilterPanel.value = false
  loadPickingOrders(supplier.name) // 使用供应商名称进行过滤
}

async function loadPickingOrders(supplierName) {
  if (loading.value) return // 防止重复加载
  
  loading.value = true
  error.value = ''
  pickingOrders.value = [] // 清空之前的数据
  
  try {
    console.log('获取供应商拣货单:', supplierName)
    
    // 从已缓存的供应商数据中查找对应的拣货单
    const supplier = suppliers.value.find(s => s.name === supplierName)
    
    if (supplier && supplier.orders && supplier.orders.length > 0) {
      // 数据已经在API层面转换，直接使用
      pickingOrders.value = supplier.orders
      
      // 初始化计划出库数量
      supplier.orders.forEach(order => {
        initializePlannedQuantity(order.id, order)
      })
      
      console.log('供应商拣货单数据:', pickingOrders.value)
      console.log('初始化的计划出库数量:', Array.from(plannedOutboundQuantities.value.entries()))
      
    } else {
      pickingOrders.value = []
      error.value = `供应商 ${supplierName} 暂无拣货单数据`
    }
  } catch (err) {
    console.error('加载拣货单失败:', err)
    error.value = `加载拣货单失败: ${err.message}`
    pickingOrders.value = []
  } finally {
    loading.value = false
  }
}

async function startPicking(order) {
  if (order.status === 'completed') return
  
  // 检查是否已选择容器
  if (!order.containerCode || order.containerCode.trim() === '') {
    alert('请先绑定容器才能开始拣货！')
    return
  }
  
  console.log('开始拣货，已绑定容器:', order.containerCode)
  
  confirmTitle.value = '确认拣货'
  confirmMessage.value = `确认开始拣货：${order.productName}？\n绑定容器：${order.containerCode}`
  confirmType.value = 'startPicking'
  currentOrder.value = order
  showConfirmModal.value = true
}

// 加载可用库位
async function loadAvailableLocations(productName, supplierName, productionDate = null) {
  loadingLocations.value = true
  availableLocations.value = []
  selectedLocation.value = null
  
  try {
    const pickingType = currentOrder.value?.pickingType || null
    console.log(`加载库位数据 - 商品: ${productName}, 供应商: ${supplierName}, 生产日期: ${productionDate}, 拣货类型: ${pickingType}`)
    const result = await wmsApi.getLocationStock(productName, supplierName, productionDate, pickingType)
    
    if (result && result.rows && result.rows.length > 0) {
      availableLocations.value = result.rows
      console.log('可用库位:', availableLocations.value)
      
      // 初始化所有库位的前端库存缓存
      result.rows.forEach(location => {
        initializeLocationStock(location.id, location.lockedStock)
      })
      
      // 如果只有一条数据，自动选中
      if (availableLocations.value.length === 1) {
        selectedLocation.value = availableLocations.value[0]
        console.log('自动选择库位:', selectedLocation.value)
        // 触发库位变化处理
        handleLocationChange()
      }
    } else {
      availableLocations.value = []
      console.log('没有找到符合条件的库位')
    }
  } catch (error) {
    console.error('加载库位失败:', error)
    availableLocations.value = []
  } finally {
    loadingLocations.value = false
  }
}

// 验证拣货库位
function validateLocationCode() {
  locationValidationError.value = ''
  
  if (!inputLocationCode.value) {
    return
  }
  
  if (!selectedLocation.value) {
    locationValidationError.value = '请先选择库位'
    return
  }
  
  const inputCode = inputLocationCode.value.trim()
  const selectedCode = selectedLocation.value.locationCode
  
  if (inputCode !== selectedCode) {
    locationValidationError.value = `库位编码不匹配，应输入：${selectedCode}`
    return
  }
  
  // 验证通过
  locationValidationError.value = ''
}

// 验证商品条码
function validateBarcode() {
  barcodeValidationError.value = ''
  
  if (!inputBarcode.value) {
    return
  }
  
  if (!currentOrder.value || !currentOrder.value.barcode) {
    barcodeValidationError.value = '商品条码信息缺失'
    return
  }
  
  const inputCode = inputBarcode.value.trim()
  const expectedCode = currentOrder.value.barcode.trim()
  
  if (inputCode !== expectedCode) {
    barcodeValidationError.value = `商品条码不匹配，应输入：${expectedCode}`
    return
  }
  
  // 验证通过
  barcodeValidationError.value = ''
}

// 获取提交按钮文本
function getSubmitButtonText() {
  if (pickingOperationState.value.isSubmitting) {
    return '提交中...'
  }
  
  if (!selectedLocation.value) {
    return '请选择库位'
  }
  
  if (!inputLocationCode.value.trim()) {
    return '请输入库位编码'
  }
  
  if (locationValidationError.value) {
    return '库位编码有误'
  }
  
  if (!inputBarcode.value.trim()) {
    return '请输入商品条码'
  }
  
  if (barcodeValidationError.value) {
    return '商品条码有误'
  }
  
  if (!pickQuantity.value || pickQuantity.value <= 0) {
    return '请输入拣货数量'
  }
  
  if (quantityError.value) {
    return '拣货数量有误'
  }
  
  if (selectedLocation.value && getDisplayLocationStock(selectedLocation.value) <= 0) {
    return '库存不足'
  }
  
  return '提交拣货'
}

// 验证拣货数量
function validatePickQuantity() {
  quantityError.value = ''
  
  if (!pickQuantity.value) {
    return
  }
  
  const quantity = parseInt(pickQuantity.value)
  
  if (isNaN(quantity) || quantity <= 0) {
    quantityError.value = '请输入有效的数量'
    return
  }
  
  if (!currentOrder.value) {
    quantityError.value = '当前拣货单信息异常'
    return
  }
  
  const remainingQuantity = getRemainingQuantity(currentOrder.value)
  
  if (quantity > remainingQuantity) {
    quantityError.value = `数量不能超过剩余拣货数量 ${remainingQuantity}`
    return
  }
  
  if (selectedLocation.value) {
    const displayStock = getDisplayLocationStock(selectedLocation.value)
    if (quantity > displayStock) {
      quantityError.value = `数量不能超过库位当前库存 ${displayStock}`
      return
    }
  }
  
  // 验证通过
  quantityError.value = ''
}

// 处理库位选择变化
function handleLocationChange() {
  console.log('选择的库位:', selectedLocation.value)
  // 重新验证数量
  validatePickQuantity()
  // 重新验证库位编码（如果已输入）
  if (inputLocationCode.value.trim()) {
    validateLocationCode()
  }
}

// 获取最大拣货数量
function getMaxPickQuantity() {
  if (!currentOrder.value) return 0
  
  const remainingQuantity = getRemainingQuantity(currentOrder.value)
  
  if (!selectedLocation.value) {
    return remainingQuantity
  }
  
  // 取剩余拣货数量和库位当前库存的最小值
  const displayStock = getDisplayLocationStock(selectedLocation.value)
  return Math.min(remainingQuantity, displayStock)
}

function completePicking(order) {
  // 添加调试信息
  console.log('completePicking被调用，订单信息:', {
    id: order.id,
    status: order.status,
    containerCode: order.containerCode,
    productName: order.productName
  })
  
  if (order.status === 'completed') {
    alert('该拣货单已完成，无需操作！')
    return
  }
  
  // 检查是否已经绑定容器
  if (order.status === 'container_bound') {
    alert('该拣货单已经绑定了容器，无法重复绑定！\n当前绑定容器：' + (order.containerCode || '未知'))
    return
  }
  
  console.log('开始绑定容器流程，订单信息:', {
    id: order.id,
    productName: order.productName,
    supplierName: order.supplierName,
    status: order.status,
    containerCode: order.containerCode
  })
  
  // 设置当前订单
  currentOrder.value = order
  
  // 显示容器选择模态框
  showContainerSelectionModal()
}

function confirmOrder(order) {
  if (order.status === 'completed') return
  
  confirmTitle.value = '确认拣货'
  confirmMessage.value = `是否确认拣货完成？`
  confirmType.value = 'confirmOrder'
  currentOrder.value = order
  showConfirmModal.value = true
}

function showSubmitConfirm() {
  // 首先检查是否可以执行拣货操作
  if (!selectedLocation.value) {
    alert('请先选择库位')
    return
  }
  
  if (!pickQuantity.value || parseInt(pickQuantity.value) <= 0) {
    alert('请输入有效的拣货数量')
    return
  }
  
  const quantity = parseInt(pickQuantity.value)
  
  // 执行安全检查
  if (!canPerformPickingOperation(selectedLocation.value.id, quantity)) {
    // 具体的错误信息已经在canPerformPickingOperation中输出
    if (pickingOperationState.value.isSubmitting) {
      alert('拣货操作正在进行中，请等待完成后再试')
    } else {
      alert('请检查库位信息')
    }
    return
  }
  
  // 重新验证数量，确保安全性
  validatePickQuantity()
  
  if (quantityError.value) {
    alert(quantityError.value)
    return
  }
  
  const remainingQuantity = getRemainingQuantity(currentOrder.value)
  const displayStock = getDisplayLocationStock(selectedLocation.value)
  
  // 最终安全检查
  if (quantity > remainingQuantity) {
    alert(`拣货数量 ${quantity} 超过剩余拣货数量 ${remainingQuantity}`)
    return
  }
  
  if (quantity > displayStock) {
    alert(`拣货数量 ${quantity} 超过库位当前库存 ${displayStock}`)
    return
  }
  
  // 记录库位操作
  recordLocationOperation(selectedLocation.value.id)
  
  confirmTitle.value = '确认提交'
  confirmMessage.value = `确认从库位 ${selectedLocation.value.locationCode} 提交 ${quantity} 件拣货？`
  confirmType.value = 'submitPicking'
  showConfirmModal.value = true
}

async function confirmAction() {
  if (confirmType.value === 'startPicking') {
    try {
      // 获取当前用户信息
      const userInfo = await wmsApi.getCurrentUserInfo()
      console.log('获取到的用户信息:', userInfo)
      
      // 向webhook发送外部门户用户信息和拣货操作信息
      const webhookData = {
        // 外部门户标准字段
        rowid: currentOrder.value.id,
        accountId: userInfo.phone, // 使用手机号作为accountId
        
        // 拣货操作信息
        action: 'start_picking',
        operatorPhone: userInfo.phone,
        operatorName: userInfo.name,
        operatorUserId: userInfo.userId,
        orderId: currentOrder.value.id,
        productName: currentOrder.value.productName,
        supplierName: currentOrder.value.supplierName,
        timestamp: new Date().toISOString()
      };
      
      console.log('发送去拣货webhook数据:', webhookData);
      await wmsApi.sendWebhook(webhookData);
      
      currentView.value = 'picking'
      pickQuantity.value = ''
      
      // 进入拣货详情页面时加载可用库位
      await loadAvailableLocations(
        currentOrder.value.productName,
        currentOrder.value.supplierName,
        currentOrder.value.productionDate
      )
    } catch (error) {
      console.error('启动拣货失败:', error)
    }
  } else if (confirmType.value === 'completePicking') {
    try {
      // 获取当前用户信息
      const userInfo = await wmsApi.getCurrentUserInfo()
      
      await wmsApi.updatePickingStatus(
        currentOrder.value.id,
        'completed',
        userInfo.phone
      )
      
      // 发送拣货完成专用webhook，包含表单ID和点击时间
      const completeWebhookData = {
        // 拣货单表单ID
        formId: currentOrder.value.id,
        // 点击时间（拣货完成时间）
        clickTime: new Date().toISOString()
      };
      
      console.log('发送拣货完成webhook数据:', completeWebhookData);
      await wmsApi.sendCompleteWebhook(completeWebhookData);
      
      currentOrder.value.status = 'completed'
      
      const orderIndex = pickingOrders.value.findIndex(o => o.id === currentOrder.value.id)
      if (orderIndex !== -1) {
        pickingOrders.value[orderIndex].status = 'completed'
      }
    } catch (error) {
      console.error('完成拣货失败:', error)
    }
  } else if (confirmType.value === 'confirmOrder') {
    try {
      // 获取当前用户信息
      const userInfo = await wmsApi.getCurrentUserInfo()
      
      // 更新拣货状态为已完成
      await wmsApi.updatePickingStatus(
        currentOrder.value.id,
        'completed',
        userInfo.phone
      )
      
      // 发送拣货确认专用webhook
      const confirmWebhookData = {
        // 拣货单表单ID
        formId: currentOrder.value.id,
        // 确认时间
        confirmTime: new Date().toISOString(),
        // 操作人员信息
        operatorPhone: userInfo.phone,
        operatorName: userInfo.name,
        // 原状态
        previousStatus: 'pending_confirm',
        // 新状态
        newStatus: 'completed'
      };
      
      console.log('发送拣货确认webhook数据:', confirmWebhookData);
      await wmsApi.sendCompleteWebhook(confirmWebhookData);
      
      // 更新本地状态
      currentOrder.value.status = 'completed'
      
      const orderIndex = pickingOrders.value.findIndex(o => o.id === currentOrder.value.id)
      if (orderIndex !== -1) {
        pickingOrders.value[orderIndex].status = 'completed'
      }
    } catch (error) {
      console.error('确认拣货失败:', error)
    }
  } else if (confirmType.value === 'submitPicking') {
    // 锁定拣货操作，防止重复提交
    lockPickingOperation()
    
    try {
      const quantity = parseInt(pickQuantity.value)
      const transactionId = pickingOperationState.value.transactionId
      
      console.log(`开始提交拣货 - 事务ID: ${transactionId}, 数量: ${quantity}, 库位: ${selectedLocation.value.id}`)
      
      // 最后一次安全检查（在锁定状态下）
      const currentStock = getCachedLocationStock(selectedLocation.value.id)
      if (quantity > currentStock) {
        throw new Error(`库存不足：当前库存 ${currentStock}，拣货数量 ${quantity}`)
      }
      
      // 获取当前用户信息
      const userInfo = await wmsApi.getCurrentUserInfo()
      
      // 提交到后端API
      await wmsApi.submitPicking(
        currentOrder.value.id,
        quantity,
        userInfo.phone
      )
      
      // 发送提交拣货专用webhook，包含事务ID
      const submitWebhookData = {
        // 拣货单表单ID
        formId: currentOrder.value.id,
        // 事务ID
        transactionId: transactionId,
        // 选定库位的库位编码
        locationCode: selectedLocation.value.locationCode,
        // 拣货数量
        pickQuantity: quantity,
        // 商品生产日期
        productionDate: currentOrder.value.productionDate || '',
        // 拣货类型
        pickingType: currentOrder.value.pickingType || '',
        // 单据类型
        documentType: currentOrder.value.documentType || '',
        // 操作人员信息
        operatorPhone: userInfo.phone,
        operatorName: userInfo.name,
        // 时间戳
        timestamp: new Date().toISOString()
      };
      
      console.log('发送提交拣货webhook数据:', submitWebhookData);
      await wmsApi.sendSubmitWebhook(submitWebhookData);
      
      // 只有在所有操作成功后才更新前端状态
      // 更新已拣数量
      currentOrder.value.pickedQuantity += quantity
      
      // 更新前端库存缓存
      const newLocationStock = updateLocationStock(selectedLocation.value.id, quantity)
      
      // 减少计划出库数量
      const newRemainingQuantity = reducePlannedQuantity(currentOrder.value.id, quantity)
      
      // 更新订单的剩余数量显示（可选，因为现在使用getRemainingQuantity计算）
      currentOrder.value.remainingQuantity = newRemainingQuantity
      
      // 检查是否完成
      if (newRemainingQuantity <= 0) {
        currentOrder.value.status = 'completed'
      }
      
      // 更新拣货单列表中对应的订单
      const orderIndex = pickingOrders.value.findIndex(o => o.id === currentOrder.value.id)
      if (orderIndex !== -1) {
        pickingOrders.value[orderIndex].pickedQuantity = currentOrder.value.pickedQuantity
        pickingOrders.value[orderIndex].remainingQuantity = newRemainingQuantity
        if (newRemainingQuantity <= 0) {
          pickingOrders.value[orderIndex].status = 'completed'
        }
      }
      
      console.log(`拣货提交成功 - 事务ID: ${transactionId}, 剩余库存: ${newLocationStock}`)
      
      currentView.value = 'orders'
      pickQuantity.value = ''
      
    } catch (error) {
      console.error('提交拣货失败:', error)
      alert(`提交失败: ${error.message}`)
    } finally {
      // 无论成功失败都要解锁操作
      unlockPickingOperation()
    }
  }
  
  closeModal()
}

async function closeModal() {
  // 如果是提交拣货操作完成后关闭弹窗，需要特殊处理
  if (confirmType.value === 'submitPicking') {
    console.log('提交拣货操作完成，等待1000ms让后端数据同步...')
    
    // 先关闭弹窗
    showConfirmModal.value = false
    confirmTitle.value = ''
    confirmMessage.value = ''
    confirmType.value = ''
    
    // 等待1000ms让后端数据同步
    await new Promise(resolve => setTimeout(resolve, 1000))
    
    // 刷新拣货单数据以获取最新状态，确保已完成的拣货单不再出现
    console.log('刷新拣货单数据，确保已完成的拣货单不再出现...')
    if (selectedSupplier.value) {
      await loadPickingOrders(selectedSupplier.value.name)
    }
    
    console.log('数据刷新完成，返回拣货单列表')
  } else {
    // 其他操作正常关闭弹窗
    showConfirmModal.value = false
    confirmTitle.value = ''
    confirmMessage.value = ''
    confirmType.value = ''
  }
}

function backToSuppliers() {
  currentView.value = 'suppliers'
  selectedSupplier.value = null
  pickingOrders.value = []
  error.value = ''
}

function backToOrders() {
  currentView.value = 'orders'
  currentOrder.value = null
  pickQuantity.value = ''
  quantityError.value = '' // 清除数量错误信息
  // 清空新增的验证字段
  inputLocationCode.value = ''
  inputBarcode.value = ''
  locationValidationError.value = ''
  barcodeValidationError.value = ''
  selectedLocation.value = null
  availableLocations.value = []
  error.value = ''
  
  // 清理过期的库位操作记录
  cleanupExpiredOperations()
  
  // 清理当前订单相关的库存缓存（可选，防止内存占用过多）
  // 这里可以选择性清理，而不是清空所有缓存
  if (locationStockCache.value.size > 50) {
    // 当缓存太多时，清理部分旧的缓存
    console.log('清理库存缓存，当前缓存数量:', locationStockCache.value.size)
    // 可以在这里实现更智能的缓存清理策略
  }
  
  // 刷新拣货单数据以获取最新状态
  if (selectedSupplier.value) {
    loadPickingOrders(selectedSupplier.value.name)
  }
}

// 清理过期的操作记录
function cleanupExpiredOperations() {
  const now = Date.now()
  const expireTime = 30000 // 30秒过期
  
  for (const [locationId, operation] of pickingOperationState.value.locationOperations.entries()) {
    if (now - operation.lastTime > expireTime) {
      pickingOperationState.value.locationOperations.delete(locationId)
    }
  }
  
  console.log('清理过期操作记录，剩余记录数:', pickingOperationState.value.locationOperations.size)
}

// 筛选相关方法
function toggleFilterPanel() {
  showFilterPanel.value = !showFilterPanel.value
}

// 刷新拣货单数据 - 相当于退出界面重新进入，但保持在拣货单界面
async function refreshPickingOrders() {
  if (!selectedSupplier.value) {
    console.warn('没有选中的供应商，无法刷新拣货单')
    return
  }
  
  console.log('刷新拣货单 - 模拟退出界面重新进入...')
  
  // 保存当前选中的供应商信息
  const currentSupplierName = selectedSupplier.value.name
  
  try {
    // 在后台进行数据重置和重新加载，保持界面在拣货单页面
    
    // 第1步：清空拣货单相关状态，但保持界面显示
    const tempSupplier = selectedSupplier.value // 临时保存供应商信息用于界面显示
    pickingOrders.value = []
    error.value = ''
    
    // 第2步：重新加载所有供应商数据（从API获取最新数据）
    // 暂时清空供应商数据以强制重新加载
    suppliers.value = []
    selectedSupplier.value = null
    
    await loadSuppliers()
    
    // 第3步：重新找到并设置供应商
    const refreshedSupplier = suppliers.value.find(s => s.name === currentSupplierName)
    if (refreshedSupplier) {
      // 重新设置选中的供应商
      selectedSupplier.value = refreshedSupplier
      
      // 第4步：重新加载该供应商的拣货单数据
      await loadPickingOrders(refreshedSupplier.name)
      
      console.log('刷新完成 - 数据已更新，界面保持在拣货单界面:', currentSupplierName)
    } else {
      console.warn('刷新后未找到原供应商:', currentSupplierName)
      // 如果找不到供应商，则回到供应商选择界面
      currentView.value = 'suppliers'
    }
    
  } catch (error) {
    console.error('刷新失败:', error)
    alert(`刷新失败: ${error.message}`)
    
    // 发生错误时，回到供应商选择界面
    currentView.value = 'suppliers'
    selectedSupplier.value = null
    pickingOrders.value = []
  }
}

function applyFilters() {
  // 筛选会通过计算属性自动应用
  console.log('应用筛选条件:', filters.value)
}

function clearFilters() {
  filters.value = {
    shippingDestination: '',
    outboundPlanNumber: '',
    pickingType: '',
    status: ''
  }
}

function getActiveFilterCount() {
  let count = 0
  if (filters.value.shippingDestination) count++
  if (filters.value.outboundPlanNumber) count++
  if (filters.value.pickingType) count++
  if (filters.value.status) count++
  return count
}

// 获取状态显示文本
function getStatusText(status) {
  const statusMap = {
    'pending': '待拣货',
    'in_progress': '拣货中',
    'completed': '已完成',
    'pending_confirm': '待确认',
    'cancelled': '已取消',
    'container_bound': '容器已绑定'
  }
  return statusMap[status] || status || '未知状态'
}

// 获取状态CSS类
function getStatusClass(status) {
  const classMap = {
    'pending': 'status-pending',
    'in_progress': 'status-progress',
    'completed': 'status-completed',
    'pending_confirm': 'status-pending-confirm',
    'cancelled': 'status-cancelled',
    'container_bound': 'status-container-bound'
  }
  return classMap[status] || 'status-unknown'
}

// 辅助函数：判断拣货单是否已完成
function isOrderCompleted(order) {
  if (!order) return false
  
  // 状态检查 - 排除待确认状态
  const orderStatus = String(order.status || '').toLowerCase();
  if (orderStatus === 'completed' || 
      orderStatus.includes('完成') || 
      orderStatus === '已完成' ||
      orderStatus === '3') {
    return true
  }
  
  // 如果状态是待确认，不认为是已完成
  if (orderStatus === 'pending_confirm' || 
      orderStatus.includes('待确认') || 
      orderStatus === '待确认' ||
      orderStatus === '5') {
    return false
  }
  
  // 数量检查：已拣数量大于等于应拣数量，但状态不是待确认
  if (order.pickedQuantity >= order.requiredQuantity && 
      order.requiredQuantity > 0 && 
      order.status !== 'pending_confirm') {
    return true
  }
  
  return false
}

// 计划出库数量管理函数
function initializePlannedQuantity(orderId, order) {
  if (!plannedOutboundQuantities.value.has(orderId)) {
    // 优先使用计划出库数，如果没有则使用应拣货数
    const plannedQuantity = order.plannedOutboundQuantity || 0
    const requiredQuantity = order.requiredQuantity || 0
    const initialQuantity = plannedQuantity > 0 ? plannedQuantity : requiredQuantity
    
    const quantity = Math.max(0, parseInt(initialQuantity) || 0)
    plannedOutboundQuantities.value.set(orderId, quantity)
    console.log(`初始化计划出库数量 - 订单ID: ${orderId}, 计划出库数: ${plannedQuantity}, 应拣货数: ${requiredQuantity}, 使用: ${quantity}`)
  }
}

function getPlannedQuantity(orderId) {
  return plannedOutboundQuantities.value.get(orderId) || 0
}

function reducePlannedQuantity(orderId, pickedQuantity) {
  const currentPlanned = getPlannedQuantity(orderId)
  const newPlanned = Math.max(0, currentPlanned - (parseInt(pickedQuantity) || 0))
  plannedOutboundQuantities.value.set(orderId, newPlanned)
  console.log(`减少计划出库数量 - 订单ID: ${orderId}, 减少: ${pickedQuantity}, 剩余: ${newPlanned}`)
  return newPlanned
}

function getRemainingQuantity(order) {
  if (!order) return 0
  
  const orderId = order.id
  const plannedQuantity = getPlannedQuantity(orderId)
  
  if (plannedQuantity > 0) {
    // 使用计划出库数量系统
    return plannedQuantity
  } else {
    // 回退到原有计算方式
    return Math.max(0, (order.requiredQuantity || 0) - (order.pickedQuantity || 0))
  }
}

function getPickingButtonTitle(order) {
  if (!order) return ''
  
  if (order.status === 'completed') {
    return '拣货已完成'
  }
  if (order.status === 'pending_confirm') {
    return '等待确认中'
  }
  if (order.status === 'container_bound') {
    return `开始拣货，已绑定容器：${order.containerCode}`
  }
  if (!order.containerCode || order.containerCode.trim() === '') {
    return '请先选择容器才能开始拣货'
  }
  return `开始拣货，当前绑定容器：${order.containerCode}`
}

// 前端库存管理函数
function initializeLocationStock(locationId, initialStock) {
  if (!locationStockCache.value.has(locationId)) {
    locationStockCache.value.set(locationId, parseInt(initialStock) || 0)
    console.log(`初始化库位库存 - 库位ID: ${locationId}, 初始库存: ${initialStock}`)
  }
}

function getCachedLocationStock(locationId) {
  return locationStockCache.value.get(locationId) || 0
}

function updateLocationStock(locationId, pickedQuantity) {
  const currentStock = getCachedLocationStock(locationId)
  const newStock = Math.max(0, currentStock - (parseInt(pickedQuantity) || 0))
  locationStockCache.value.set(locationId, newStock)
  console.log(`更新库位库存 - 库位ID: ${locationId}, 减少: ${pickedQuantity}, 剩余: ${newStock}`)
  return newStock
}

function getDisplayLocationStock(location) {
  if (!location) return 0
  // 优先使用缓存的库存数量，如果没有缓存则使用原始API数据
  const cachedStock = getCachedLocationStock(location.id)
  return cachedStock > 0 ? cachedStock : (location.lockedStock || 0)
}

// 拣货操作安全检查和防重复提交机制
function canPerformPickingOperation(locationId, quantity) {
  const now = Date.now()
  
  // 检查是否正在提交
  if (pickingOperationState.value.isSubmitting) {
    console.warn('拣货操作正在进行中，请等待...')
    return false
  }
  
  // 检查操作冷却时间
  if (now - pickingOperationState.value.lastOperationTime < pickingOperationState.value.operationCooldown) {
    console.warn('操作间隔时间不足，请稍后再试')
    return false
  }
  
  // 检查库位库存是否足够
  const currentStock = getCachedLocationStock(locationId)
  if (quantity > currentStock) {
    console.warn(`库位库存不足，当前库存: ${currentStock}, 拣货数量: ${quantity}`)
    return false
  }
  
  // 检查库位是否在短时间内被多次操作
  const locationOp = pickingOperationState.value.locationOperations.get(locationId)
  if (locationOp) {
    const timeSinceLastOp = now - locationOp.lastTime
    if (timeSinceLastOp < 1000 && locationOp.count >= 2) { // 1秒内不能超过2次操作
      console.warn('同一库位操作过于频繁')
      return false
    }
  }
  
  return true
}

function recordLocationOperation(locationId) {
  const now = Date.now()
  const existing = pickingOperationState.value.locationOperations.get(locationId)
  
  if (existing && now - existing.lastTime < 5000) { // 5秒内的操作计数累加
    existing.count += 1
    existing.lastTime = now
  } else {
    pickingOperationState.value.locationOperations.set(locationId, {
      count: 1,
      lastTime: now
    })
  }
}

function generateTransactionId() {
  return `tx_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`
}

function lockPickingOperation() {
  pickingOperationState.value.isSubmitting = true
  pickingOperationState.value.lastOperationTime = Date.now()
  pickingOperationState.value.transactionId = generateTransactionId()
  console.log('拣货操作已锁定，事务ID:', pickingOperationState.value.transactionId)
}

function unlockPickingOperation() {
  pickingOperationState.value.isSubmitting = false
  pickingOperationState.value.transactionId = null
  console.log('拣货操作已解锁')
}

// 容器选择相关函数
async function showContainerSelectionModal() {
  console.log('=== 开始显示容器选择模态框 ===')
  
  // 重置状态
  loadingContainers.value = true
  availableContainers.value = []
  selectedContainer.value = null
  showContainerModal.value = true
  
  console.log('初始状态:', {
    loadingContainers: loadingContainers.value,
    availableContainers: availableContainers.value.length,
    selectedContainer: selectedContainer.value,
    showContainerModal: showContainerModal.value
  })
  
  try {
    console.log('加载可用容器数据...')
    
    // 获取当前订单的配送站点信息
    const orderDeliveryStation = currentOrder.value?.shippingDestination || ''
    console.log('当前订单配送站点:', orderDeliveryStation)
    
    const result = await wmsApi.getAvailableContainers(orderDeliveryStation)
    
    console.log('容器API返回结果:', result)
    console.log('result.rows存在?', !!result?.rows)
    console.log('result.rows长度:', result?.rows?.length)
    
    if (result && result.rows && result.rows.length > 0) {
      availableContainers.value = result.rows
      console.log('设置可用容器:', availableContainers.value)
      console.log('Vue响应式状态 - 可用容器数量:', availableContainers.value.length)
    } else {
      availableContainers.value = []
      console.log('没有找到可用容器，设置为空数组')
      
      // 额外调试信息
      if (result) {
        console.log('result存在但数据异常:', {
          hasRows: !!result.rows,
          rowsType: typeof result.rows,
          rowsLength: result.rows?.length,
          resultKeys: Object.keys(result),
          warning: result.warning
        });
      }
      
      // 如果没有找到容器，给出具体提示
      if (orderDeliveryStation) {
        console.log(`未找到配送站点为 "${orderDeliveryStation}" 的可用容器`)
      }
    }
  } catch (error) {
    console.error('加载容器数据失败:', error)
    console.error('错误堆栈:', error.stack)
    availableContainers.value = []
    alert(`加载容器数据失败: ${error.message}`)
  } finally {
    console.log('容器加载完成，最终状态:', {
      loadingContainers: loadingContainers.value,
      availableContainersCount: availableContainers.value?.length || 0,
      orderDeliveryStation: currentOrder.value?.shippingDestination
    });
    loadingContainers.value = false
  }
}

function selectContainer(container) {
  if (!container) {
    console.error('⚠️ 尝试选择空容器')
    return
  }
  
  if (!container.containerCode || !container.containerCode.trim()) {
    console.error('⚠️ 尝试选择无效容器（无容器码）:', container)
    alert('选择的容器信息无效，请重新选择')
    return
  }
  
  selectedContainer.value = container
  console.log('✅ 选择容器:', {
    id: container.id,
    containerCode: container.containerCode,
    status: container.status,
    deliveryStation: container.deliveryStation
  })
}

function closeContainerModal() {
  showContainerModal.value = false
  selectedContainer.value = null
  availableContainers.value = []
  containerSearchQuery.value = ''
}

async function confirmContainerBinding() {
  if (!selectedContainer.value) {
    alert('请选择一个容器')
    return
  }
  
  if (!currentOrder.value) {
    alert('当前订单信息异常')
    return
  }
  
  // 保存选中的容器信息，防止在执行过程中被清空
  const containerInfo = {
    id: selectedContainer.value.id,
    containerCode: selectedContainer.value.containerCode,
    status: selectedContainer.value.status,
    deliveryStation: selectedContainer.value.deliveryStation || ''
  }
  
  console.log('=== 开始绑定容器流程 ===')
  console.log('选择的容器:', containerInfo)
  console.log('当前订单:', currentOrder.value)
  
  // 验证容器信息完整性
  if (!containerInfo.containerCode || !containerInfo.containerCode.trim()) {
    alert('选择的容器信息不完整，请重新选择')
    return
  }
  
  try {
    // 获取当前用户信息
    const userInfo = await wmsApi.getCurrentUserInfo()
    console.log('当前用户信息:', userInfo)
    
    // 步骤1: 先更新拣货单的容器码字段
    console.log('步骤1: 更新拣货单容器码')
    console.log('使用容器码:', containerInfo.containerCode)
    await wmsApi.updatePickingOrderContainerCode(
      currentOrder.value.id,
      containerInfo.containerCode
    )
    console.log('✅ 拣货单容器码更新完成')
    
    // 步骤2: 更新拣货状态为已完成
    console.log('步骤2: 更新拣货状态')
    await wmsApi.updatePickingStatus(
      currentOrder.value.id,
      'completed',
      userInfo.phone
    )
    console.log('✅ 拣货状态更新完成')
    
    // 步骤3: 发送绑定容器专用webhook，使用标准的明道云外部门户字段格式
    console.log('步骤3: 发送绑定容器webhook')
    const containerWebhookData = {
      // 外部门户标准字段
      rowid: currentOrder.value.id,
      accountId: userInfo.phone, // 使用手机号作为accountId
      
      // 绑定容器操作信息
      action: 'bind_container',
      operatorPhone: userInfo.phone,
      operatorName: userInfo.name,
      operatorUserId: userInfo.userId,
      orderId: currentOrder.value.id,
      containerCode: containerInfo.containerCode,
      containerStatus: containerInfo.status,
      containerDeliveryStation: containerInfo.deliveryStation,
      productName: currentOrder.value.productName,
      supplierName: currentOrder.value.supplierName,
      pickingType: currentOrder.value.pickingType,
      documentType: currentOrder.value.documentType,
      shippingDestination: currentOrder.value.shippingDestination,
      timestamp: new Date().toISOString()
    };
    
    console.log('发送绑定容器webhook数据:', containerWebhookData);
    
    // 验证关键字段
    console.log('=== Webhook数据验证 ===');
    console.log('拣货单记录ID (rowid):', containerWebhookData.rowid);
    console.log('用户账户ID (accountId):', containerWebhookData.accountId);
    console.log('容器码 (containerCode):', containerWebhookData.containerCode);
    console.log('操作类型 (action):', containerWebhookData.action);
    console.log('操作人手机号 (operatorPhone):', containerWebhookData.operatorPhone);
    console.log('操作人姓名 (operatorName):', containerWebhookData.operatorName);
    console.log('商品名称 (productName):', containerWebhookData.productName);
    console.log('供应商名称 (supplierName):', containerWebhookData.supplierName);
    console.log('拣货类型 (pickingType):', containerWebhookData.pickingType);
    console.log('发运目的地 (shippingDestination):', containerWebhookData.shippingDestination);
    console.log('容器状态 (containerStatus):', containerWebhookData.containerStatus);
    console.log('容器配送站点 (containerDeliveryStation):', containerWebhookData.containerDeliveryStation);
    console.log('时间戳 (timestamp):', containerWebhookData.timestamp);
    console.log('======================');
    
    // 验证数据完整性
    const missingFields = [];
    if (!containerWebhookData.rowid) missingFields.push('rowid');
    if (!containerWebhookData.accountId) missingFields.push('accountId');
    if (!containerWebhookData.containerCode) missingFields.push('containerCode');
    if (!containerWebhookData.operatorPhone) missingFields.push('operatorPhone');
    
    if (missingFields.length > 0) {
      console.error('⚠️ 警告：以下关键字段缺失:', missingFields);
      alert(`警告：webhook数据不完整，缺少字段: ${missingFields.join(', ')}`);
    } else {
      console.log('✅ 所有关键字段验证通过');
    }
    
    await wmsApi.sendCompleteWebhook(containerWebhookData);
    console.log('✅ Webhook发送完成')
    
    // 步骤4: 更新本地状态 - 使用container_bound状态而不是completed
    console.log('步骤4: 更新本地状态')
    currentOrder.value.status = 'container_bound' // 使用新状态
    currentOrder.value.containerCode = containerInfo.containerCode // 确保容器码被设置
    
    const orderIndex = pickingOrders.value.findIndex(o => o.id === currentOrder.value.id)
    if (orderIndex !== -1) {
      pickingOrders.value[orderIndex].status = 'container_bound' // 使用新状态
      // 更新本地订单的容器码显示
      pickingOrders.value[orderIndex].containerCode = containerInfo.containerCode
      console.log('✅ 本地订单状态更新:', pickingOrders.value[orderIndex])
    }
    console.log('✅ 本地状态更新完成')
    
    // 关闭模态框
    closeContainerModal()
    
    console.log('=== 容器绑定流程完成 ===')
    alert(`成功绑定容器：${containerInfo.containerCode}`)
    
  } catch (error) {
    console.error('❌ 绑定容器失败:', error)
    console.error('错误详情:', error.stack)
    console.error('容器信息:', containerInfo)
    console.error('selectedContainer.value状态:', selectedContainer.value)
    alert(`绑定容器失败: ${error.message}`)
  }
}

// 辅助函数：从明道云控件数组中获取字段值
function getFieldValue(controls, fieldName) {
  if (!controls || !Array.isArray(controls)) return null
  
  const control = controls.find(c => c.controlName === fieldName)
  return control ? control.value : null
}

// 辅助函数：根据控件ID获取字段值
function getFieldValueById(controls, controlId) {
  if (!controls || !Array.isArray(controls)) return null
  
  const control = controls.find(c => c.controlId === controlId)
  return control ? control.value : null
}
</script>

<style scoped>
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

.wms-app {
  min-height: 100vh;
  background-color: #f5f5f5;
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
}

.header {
  background-color: #f8b300;
  padding: 1rem;
  color: white;
  display: flex;
  align-items: center;
  gap: 1rem;
}

.header h1, .header h2 {
  margin: 0;
  font-weight: 600;
}

.config-btn {
  background: rgba(255, 255, 255, 0.2);
  border: 1px solid rgba(255, 255, 255, 0.3);
  color: white;
  padding: 0.5rem 1rem;
  border-radius: 6px;
  cursor: pointer;
  font-size: 0.9rem;
  transition: background-color 0.2s;
}

.config-btn:hover {
  background: rgba(255, 255, 255, 0.3);
}

.back-btn {
  background: rgba(255, 255, 255, 0.2);
  border: 1px solid rgba(255, 255, 255, 0.3);
  color: white;
  padding: 0.5rem 1rem;
  border-radius: 6px;
  cursor: pointer;
  font-size: 0.9rem;
  transition: background-color 0.2s;
}

.back-btn:hover {
  background: rgba(255, 255, 255, 0.3);
}

.loading, .error-message {
  text-align: center;
  padding: 2rem;
  margin: 1rem;
  border-radius: 8px;
}

.loading {
  background: #f8f9fa;
  color: #666;
}

.error-message {
  background: #f8d7da;
  color: #721c24;
  border: 1px solid #f5c6cb;
}

.retry-btn {
  background: #dc3545;
  color: white;
  border: none;
  padding: 0.5rem 1rem;
  border-radius: 4px;
  cursor: pointer;
  margin-top: 1rem;
  transition: background-color 0.2s;
}

.retry-btn:hover {
  background: #c82333;
}

.debug-panel {
  background: white;
  margin: 1rem;
  padding: 1.5rem;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  border-left: 4px solid #17a2b8;
}

.debug-panel h3 {
  color: #333;
  margin-bottom: 1rem;
}

.test-btn {
  background: #17a2b8;
  color: white;
  border: none;
  padding: 0.75rem 1.5rem;
  border-radius: 6px;
  cursor: pointer;
  font-weight: 500;
  transition: background-color 0.2s;
  margin-bottom: 1rem;
}

.test-btn:hover:not(:disabled) {
  background: #138496;
}

.test-btn:disabled {
  background: #6c757d;
  cursor: not-allowed;
}

.debug-info {
  margin-top: 1rem;
}

.debug-info h4 {
  color: #333;
  margin-bottom: 0.5rem;
}

.debug-info pre {
  background: #f8f9fa;
  border: 1px solid #e9ecef;
  border-radius: 4px;
  padding: 1rem;
  font-size: 0.85rem;
  overflow-x: auto;
  max-height: 400px;
}

.supplier-list {
  min-height: 100vh;
}

.supplier-grid {
  padding: 2rem;
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 1.5rem;
  max-width: 1200px;
  margin: 0 auto;
}

.supplier-card {
  background: white;
  border-radius: 12px;
  padding: 2rem;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  cursor: pointer;
  transition: all 0.3s ease;
  border-left: 4px solid #f8b300;
}

.supplier-card:hover {
  transform: translateY(-4px);
  box-shadow: 0 8px 25px rgba(248, 179, 0, 0.2);
}

.supplier-name {
  font-size: 1.5rem;
  font-weight: 600;
  color: #333;
  margin-bottom: 0.5rem;
}

.order-count {
  color: #666;
  font-size: 1rem;
}

.order-list {
  min-height: 100vh;
}

.order-items {
  padding: 1rem;
}

.order-item {
  background: white;
  border-radius: 8px;
  padding: 1.5rem;
  margin-bottom: 1rem;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.order-info {
  flex: 1;
}

.product-name {
  font-size: 1.2rem;
  font-weight: 600;
  color: #333;
  margin-bottom: 0.75rem;
}

.order-meta {
  display: grid;
  grid-template-columns: 1fr 1fr 1fr;
  gap: 0.5rem;
  margin-bottom: 0.75rem;
}

.meta-item {
  display: flex;
  align-items: center;
  font-size: 0.9rem;
}

.meta-label {
  color: #666;
  font-weight: 500;
  margin-right: 0.5rem;
  min-width: 80px;
}

.meta-value {
  color: #333;
  font-weight: 400;
}

.meta-value.status {
  padding: 0.2rem 0.5rem;
  border-radius: 12px;
  font-size: 0.8rem;
  font-weight: 500;
}

.status-pending {
  background: #fff3cd;
  color: #856404;
}

.status-progress {
  background: #d1ecf1;
  color: #0c5460;
}

.status-completed {
  background: #d4edda;
  color: #155724;
}

.status-pending-confirm {
  background: #e2e3e5;
  color: #383d41;
  border: 1px solid #007bff;
}

.status-container-bound {
  background: #d1ecf1;
  color: #0c5460;
  border: 1px solid #17a2b8;
  font-weight: 600;
}

/* 容器码显示样式 */
.container-code {
  color: #28a745;
  font-weight: 600;
  background: rgba(40, 167, 69, 0.1);
  padding: 0.2rem 0.5rem;
  border-radius: 4px;
}

.no-container {
  color: #dc3545;
  font-weight: 600;
  background: rgba(220, 53, 69, 0.1);
  padding: 0.2rem 0.5rem;
  border-radius: 4px;
}

.container-warning {
  animation: blink-warning 1.5s ease-in-out infinite;
}

@keyframes blink-warning {
  0%, 50% { opacity: 1; }
  25%, 75% { opacity: 0.7; }
}

.status-cancelled {
  background: #f8d7da;
  color: #721c24;
}

.status-unknown {
  background: #e2e3e5;
  color: #383d41;
}

/* 筛选面板样式 */
.header-buttons {
  display: flex;
  gap: 0.5rem;
  margin-left: auto;
  align-items: center;
}

.refresh-btn {
  background: #28a745;
  color: white;
  border: none;
  padding: 0.5rem 1rem;
  border-radius: 6px;
  cursor: pointer;
  font-weight: 500;
  transition: background-color 0.2s;
  position: relative;
}

.refresh-btn:hover:not(:disabled) {
  background: #218838;
}

.refresh-btn:disabled {
  background: #6c757d;
  cursor: not-allowed;
  opacity: 0.7;
}

.filter-toggle-btn {
  background: #17a2b8;
  color: white;
  border: none;
  padding: 0.5rem 1rem;
  border-radius: 6px;
  cursor: pointer;
  font-weight: 500;
  transition: background-color 0.2s;
  position: relative;
}

.filter-toggle-btn:hover {
  background: #138496;
}

.filter-count {
  background: #dc3545;
  color: white;
  border-radius: 50%;
  padding: 0.2rem 0.4rem;
  font-size: 0.7rem;
  margin-left: 0.5rem;
}

.filter-panel {
  background: #f8f9fa;
  border: 1px solid #dee2e6;
  border-radius: 8px;
  padding: 1rem;
  margin: 1rem;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.filter-row {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 1rem;
  margin-bottom: 1rem;
}

.filter-row:last-of-type {
  margin-bottom: 1.5rem;
}

.filter-item {
  display: flex;
  flex-direction: column;
}

.filter-item label {
  font-weight: 600;
  color: #333;
  margin-bottom: 0.5rem;
  font-size: 0.9rem;
}

.filter-item select {
  padding: 0.6rem;
  border: 1px solid #ced4da;
  border-radius: 6px;
  font-size: 0.9rem;
  background: white;
  transition: border-color 0.2s;
}

.filter-item select:focus {
  outline: none;
  border-color: #17a2b8;
  box-shadow: 0 0 0 0.2rem rgba(23, 162, 184, 0.25);
}

.filter-actions {
  display: flex;
  gap: 1rem;
  justify-content: center;
}

.clear-filters-btn, .close-filter-btn {
  padding: 0.6rem 1.2rem;
  border: none;
  border-radius: 6px;
  cursor: pointer;
  font-weight: 500;
  transition: background-color 0.2s;
}

.clear-filters-btn {
  background: #dc3545;
  color: white;
}

.clear-filters-btn:hover {
  background: #c82333;
}

.close-filter-btn {
  background: #6c757d;
  color: white;
}

.close-filter-btn:hover {
  background: #5a6268;
}

.quantity-info {
  display: flex;
  gap: 1rem;
}

.quantity-info span {
  color: #888;
  font-size: 0.9rem;
}

.order-actions {
  margin-left: 1rem;
  display: flex;
  gap: 0.5rem;
  flex-direction: column;
}

.pick-btn, .complete-btn {
  border: none;
  padding: 1rem 1.5rem;
  border-radius: 8px;
  cursor: pointer;
  font-weight: 600;
  font-size: 1rem;
  transition: all 0.2s ease;
  color: white;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  min-height: 48px; /* 确保移动端触摸友好 */
  position: relative;
  overflow: hidden;
}

.pick-btn {
  background: linear-gradient(135deg, #f8b300 0%, #e6a200 100%);
  border-left: 4px solid #d4950a;
}

.pick-btn:hover:not(:disabled) {
  background: linear-gradient(135deg, #e6a200 0%, #d49200 100%);
  transform: translateY(-1px);
  box-shadow: 0 4px 8px rgba(248, 179, 0, 0.3);
}

.pick-btn:active:not(:disabled) {
  transform: translateY(0);
  box-shadow: 0 2px 4px rgba(248, 179, 0, 0.2);
}

/* 未绑定容器的按钮样式 */
.pick-btn.no-container {
  background: linear-gradient(135deg, #ffc107 0%, #ffca2c 100%);
  color: #212529;
  border: 2px solid #fd7e14;
  border-left: 4px solid #fd7e14;
  animation: pulse-warning 2s infinite;
}

.pick-btn.no-container:hover:not(:disabled) {
  background: linear-gradient(135deg, #ffca2c 0%, #ffd43b 100%);
  transform: none;
  box-shadow: 0 4px 8px rgba(255, 193, 7, 0.3);
}

.pick-btn.no-container:disabled {
  background: #adb5bd;
  color: #6c757d;
  border: 2px solid #dee2e6;
  border-left: 4px solid #dee2e6;
  animation: none;
}

@keyframes pulse-warning {
  0%, 100% { 
    box-shadow: 0 0 0 0 rgba(255, 193, 7, 0.7);
  }
  50% { 
    box-shadow: 0 0 0 8px rgba(255, 193, 7, 0);
  }
}

.complete-btn {
  background: linear-gradient(135deg, #28a745 0%, #218838 100%);
  border-left: 4px solid #1e7e34;
}

.complete-btn:hover:not(:disabled) {
  background: linear-gradient(135deg, #218838 0%, #1e7e34 100%);
  transform: translateY(-1px);
  box-shadow: 0 4px 8px rgba(40, 167, 69, 0.3);
}

.complete-btn:active:not(:disabled) {
  transform: translateY(0);
  box-shadow: 0 2px 4px rgba(40, 167, 69, 0.2);
}

.confirm-btn {
  background: linear-gradient(135deg, #007bff 0%, #0056b3 100%);
  border-left: 4px solid #004085;
  color: white;
  border: none;
  padding: 1rem 1.5rem;
  border-radius: 8px;
  cursor: pointer;
  font-weight: 600;
  font-size: 1rem;
  transition: all 0.2s ease;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  min-height: 48px;
  position: relative;
  overflow: hidden;
}

.confirm-btn:hover:not(:disabled) {
  background: linear-gradient(135deg, #0056b3 0%, #004085 100%);
  transform: translateY(-1px);
  box-shadow: 0 4px 8px rgba(0, 123, 255, 0.3);
}

.confirm-btn:active:not(:disabled) {
  transform: translateY(0);
  box-shadow: 0 2px 4px rgba(0, 123, 255, 0.2);
}

.confirm-btn:before {
  content: "✓ ";
  margin-right: 0.5rem;
}

.pick-btn:disabled, .complete-btn:disabled, .confirm-btn:disabled {
  background: #e9ecef;
  color: #6c757d;
  cursor: not-allowed;
  transform: none;
  box-shadow: none;
  border-left: 4px solid #dee2e6;
}

/* 已绑定容器的按钮特殊样式 */
.complete-btn.container-bound {
  background: linear-gradient(135deg, #17a2b8 0%, #138496 100%) !important;
  color: white !important;
  border-left: 4px solid #117a8b !important;
  cursor: not-allowed;
}

.complete-btn.container-bound:before {
  content: "🔗 ";
  margin-right: 0.5rem;
}

/* 添加按钮图标效果 */
.pick-btn:before {
  content: "📦 ";
  margin-right: 0.5rem;
}

.complete-btn:before {
  content: "✅ ";
  margin-right: 0.5rem;
}

.picking-detail {
  min-height: 100vh;
}

.product-info, .location-info {
  background: white;
  margin: 0.5rem 1rem;
  padding: 1rem;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.info-item, .location-item {
  display: flex;
  margin-bottom: 0.5rem;
  align-items: center;
}

.info-item:last-child, .location-item:last-child {
  margin-bottom: 0;
}

.info-item label, .location-item label {
  font-weight: 600;
  color: #333;
  width: 100px;
  flex-shrink: 0;
  font-size: 0.9rem;
}

.info-item span, .location-item span {
  color: #666;
  font-size: 0.9rem;
}

.pick-form {
  background: white;
  margin: 0.5rem 1rem;
  padding: 1rem;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.form-group {
  margin-bottom: 1rem;
}

.form-group label {
  display: block;
  font-weight: 600;
  color: #333;
  margin-bottom: 0.5rem;
}

.form-group input {
  width: 100%;
  padding: 0.75rem;
  border: 2px solid #ddd;
  border-radius: 6px;
  font-size: 1rem;
  transition: border-color 0.2s;
}

.form-group input:focus {
  outline: none;
  border-color: #f8b300;
}

.location-select {
  width: 100%;
  padding: 0.75rem;
  border: 2px solid #ddd;
  border-radius: 6px;
  font-size: 1rem;
  background: white;
  transition: border-color 0.2s;
}

.location-select:focus {
  outline: none;
  border-color: #f8b300;
}

.location-select:disabled {
  background: #f5f5f5;
  color: #999;
  cursor: not-allowed;
}

.submit-btn {
  width: 80%;
  height: 8vh;
  background: #28a745 !important;
  color: white;
  border: none;
  border-radius: 8px;
  font-size: 1.1rem;
  font-weight: 600;
  cursor: pointer;
  transition: none;
  display: block;
  margin: 0 auto;
}

.submit-btn:hover:not(:disabled) {
  background: #28a745 !important;
}

.submit-btn:disabled {
  background: #28a745 !important;
  color: #ffffff !important;
  cursor: not-allowed;
  opacity: 0.6;
}

.debug-buttons {
  display: flex;
  gap: 1rem;
  margin-top: 1rem;
  justify-content: center;
}

.debug-btn {
  background: #17a2b8;
  color: white;
  border: none;
  padding: 0.5rem 1rem;
  border-radius: 4px;
  cursor: pointer;
  font-size: 0.9rem;
  transition: background-color 0.2s;
}

.debug-btn:hover:not(:disabled) {
  background: #138496;
}

.debug-btn:disabled {
  background: #6c757d;
  cursor: not-allowed;
}

.location-debug-info {
  margin-top: 1rem;
  background: #f8f9fa;
  border: 1px solid #dee2e6;
  border-radius: 4px;
  padding: 1rem;
}

.location-debug-info h4 {
  color: #495057;
  margin-bottom: 0.5rem;
  font-size: 1rem;
}

.location-debug-info pre {
  background: #ffffff;
  border: 1px solid #dee2e6;
  border-radius: 4px;
  padding: 0.75rem;
  font-size: 0.8rem;
  overflow-x: auto;
  max-height: 400px;
  margin: 0;
}

/* 库位选择优化样式 */
.single-location {
  background: #e8f5e8;
  border: 2px solid #28a745;
  border-radius: 6px;
  padding: 0.75rem;
  color: #155724;
  font-weight: 500;
}

.single-location.stock-insufficient {
  background: #f8d7da;
  border: 2px solid #dc3545;
  color: #721c24;
}

.stock-warning {
  color: #dc3545;
  font-weight: 600;
}

.no-location {
  background: #f8d7da;
  border: 2px solid #dc3545;
  border-radius: 6px;
  padding: 0.75rem;
  color: #721c24;
  text-align: center;
}

.loading-location {
  background: #d1ecf1;
  border: 2px solid #17a2b8;
  border-radius: 6px;
  padding: 0.75rem;
  color: #0c5460;
  text-align: center;
}

/* 数量输入优化样式 */
.form-group input.error {
  border-color: #dc3545;
  box-shadow: 0 0 0 0.2rem rgba(220, 53, 69, 0.25);
}

.quantity-info {
  margin-top: 0.5rem;
  font-size: 0.9rem;
}

.limit-info {
  color: #28a745;
  font-weight: 600;
  margin-right: 0.5rem;
}

.breakdown {
  color: #6c757d;
  font-size: 0.85rem;
}

.error-message {
  margin-top: 0.5rem;
  color: #dc3545;
  font-size: 0.85rem;
  font-weight: 500;
  background: #f8d7da;
  border: 1px solid #f5c6cb;
  border-radius: 4px;
  padding: 0.5rem;
}

/* 操作状态提示样式 */
.operation-status {
  margin-top: 0.5rem;
  padding: 0.5rem;
  border-radius: 4px;
  font-size: 0.85rem;
  font-weight: 500;
  display: flex;
  align-items: center;
  gap: 0.5rem;
  background: #d1ecf1;
  border: 1px solid #bee5eb;
  color: #0c5460;
}

.status-icon {
  font-size: 1rem;
}

.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
}

.modal-content {
  background: white;
  border-radius: 12px;
  padding: 2rem;
  max-width: 400px;
  width: 90%;
  box-shadow: 0 20px 60px rgba(0, 0, 0, 0.3);
}

.modal-content h3 {
  color: #333;
  margin-bottom: 1rem;
  font-size: 1.3rem;
}

.modal-content p {
  color: #666;
  margin-bottom: 2rem;
  line-height: 1.5;
}

.modal-actions {
  display: flex;
  gap: 1rem;
  justify-content: flex-end;
}

.cancel-btn, .confirm-btn {
  padding: 0.75rem 1.5rem;
  border: none;
  border-radius: 6px;
  cursor: pointer;
  font-weight: 500;
  transition: all 0.2s;
}

.cancel-btn {
  background: #f8f9fa;
  color: #333;
  border: 1px solid #ddd;
}

.cancel-btn:hover {
  background: #e9ecef;
}

.confirm-btn {
  background: #f8b300;
  color: white;
}

.confirm-btn:hover {
  background: #e6a200;
}

/* 容器选择模态框样式 */
.container-modal-content {
  background: white;
  border-radius: 12px;
  padding: 2rem;
  max-width: 500px;
  width: 90%;
  max-height: 80vh;
  overflow-y: auto;
  box-shadow: 0 20px 60px rgba(0, 0, 0, 0.3);
}

.container-modal-content h3 {
  color: #333;
  margin-bottom: 1rem;
  font-size: 1.3rem;
  text-align: center;
}

.container-modal-content p {
  color: #666;
  margin-bottom: 1.5rem;
  line-height: 1.5;
  text-align: center;
}

.loading-containers, .no-containers {
  text-align: center;
  padding: 2rem;
  color: #666;
}

.container-list {
  max-height: 300px;
  overflow-y: auto;
  margin-bottom: 2rem;
  border: 1px solid #e9ecef;
  border-radius: 8px;
}

.container-item {
  padding: 1rem;
  border-bottom: 1px solid #e9ecef;
  cursor: pointer;
  transition: all 0.2s ease;
}

.container-item:last-child {
  border-bottom: none;
}

.container-item:hover {
  background-color: #f8f9fa;
}

.container-item.selected {
  background-color: #e3f2fd;
  border-left: 4px solid #2196f3;
}

.container-info {
  width: 100%;
}

.container-code {
  font-weight: 600;
  color: #333;
  font-size: 1.1rem;
  margin-bottom: 0.5rem;
}

.container-details {
  display: flex;
  flex-direction: column;
  gap: 0.25rem;
}

.container-status {
  color: #666;
  font-size: 0.9rem;
}

.container-station {
  color: #666;
  font-size: 0.9rem;
}

.container-station.empty {
  color: #999;
  font-style: italic;
}

/* 容器搜索栏样式 */
.container-search {
  margin-bottom: 1rem;
  padding: 1rem;
  background: #f8f9fa;
  border-radius: 8px;
  border: 1px solid #dee2e6;
}

.search-input {
  width: 100%;
  padding: 0.75rem 1rem;
  border: 2px solid #ddd;
  border-radius: 8px;
  font-size: 1rem;
  transition: border-color 0.2s;
  box-sizing: border-box;
}

.search-input:focus {
  outline: none;
  border-color: #17a2b8;
  box-shadow: 0 0 0 0.2rem rgba(23, 162, 184, 0.25);
}

.search-input::placeholder {
  color: #999;
}

.search-info {
  margin-top: 0.5rem;
  font-size: 0.85rem;
  color: #28a745;
  text-align: center;
  font-weight: 500;
}

.search-hint {
  margin-top: 0.5rem;
  font-size: 0.85rem;
  color: #999;
  text-align: center;
  font-style: italic;
}

.no-search-results {
  text-align: center;
  padding: 2rem;
  color: #666;
}

.no-search-results p {
  margin: 0.5rem 0;
}

.search-suggestion {
  font-size: 0.85rem;
  color: #999;
  font-style: italic;
}

@media (max-width: 768px) {
  .supplier-grid {
    grid-template-columns: 1fr;
    padding: 1rem;
  }
  
  /* 移动端筛选样式优化 */
  .header {
    flex-wrap: wrap;
    gap: 0.5rem;
  }
  
  .header-buttons {
    order: 3;
    width: 100%;
    margin-left: 0;
    margin-top: 0.5rem;
    justify-content: center;
    gap: 0.75rem;
  }
  
  .refresh-btn {
    flex: 1;
    padding: 0.75rem;
    font-size: 1rem;
    min-height: 48px;
  }
  
  .filter-toggle-btn {
    flex: 1;
    padding: 0.75rem;
    font-size: 1rem;
    min-height: 48px;
  }
  
  .filter-panel {
    margin: 0.5rem;
    padding: 0.75rem;
    position: sticky;
    top: 0;
    z-index: 100;
    background: #ffffff;
    border: 2px solid #17a2b8;
  }
  
  .filter-row {
    grid-template-columns: 1fr;
    gap: 0.75rem;
    margin-bottom: 0.75rem;
  }
  
  .filter-item label {
    font-size: 0.85rem;
    margin-bottom: 0.25rem;
  }
  
  .filter-item select {
    padding: 0.75rem;
    font-size: 0.9rem;
    border-width: 2px;
  }
  
  .filter-actions {
    flex-direction: column;
    gap: 0.5rem;
  }
  
  .clear-filters-btn, .close-filter-btn {
    width: 100%;
    padding: 0.75rem;
    font-size: 0.9rem;
  }
  
  .order-item {
    flex-direction: column;
    align-items: flex-start;
    gap: 1rem;
    padding: 1.5rem;
  }
  
  .order-actions {
    margin-left: 0;
    width: 100%;
    flex-direction: column;
    gap: 0.75rem;
  }
  
  .pick-btn, .complete-btn, .confirm-btn {
    width: 100%;
    padding: 1.25rem 1.5rem;
    font-size: 1.1rem;
    min-height: 56px; /* 更大的触摸目标 */
    border-radius: 12px;
  }
  
  /* 移动端按钮优先级视觉设计 */
  .pick-btn {
    order: 1; /* 去拣货按钮在上方，更常用 */
    background: linear-gradient(135deg, #f8b300 0%, #e6a200 100%);
    box-shadow: 0 3px 6px rgba(248, 179, 0, 0.2);
  }
  
  .complete-btn {
    order: 2; /* 完成按钮在下方 */
    background: linear-gradient(135deg, #6c757d 0%, #5a6268 100%);
    border-left: 4px solid #495057;
  }
  
  .confirm-btn {
    order: 1; /* 确认按钮优先显示 */
    width: 100%;
    padding: 1.25rem 1.5rem;
    font-size: 1.1rem;
    min-height: 56px; /* 更大的触摸目标 */
    border-radius: 12px;
    background: linear-gradient(135deg, #007bff 0%, #0056b3 100%);
    border-left: 4px solid #004085;
    color: white;
    border: none;
    cursor: pointer;
    font-weight: 600;
    transition: all 0.2s ease;
    box-shadow: 0 3px 6px rgba(0, 123, 255, 0.2);
    position: relative;
    overflow: hidden;
  }
  
  .confirm-btn:before {
    content: "✓ ";
    margin-right: 0.5rem;
  }

  .confirm-btn:hover:not(:disabled) {
    background: linear-gradient(135deg, #0056b3 0%, #004085 100%);
    transform: translateY(-1px);
    box-shadow: 0 4px 8px rgba(0, 123, 255, 0.3);
  }

  .complete-btn:hover:not(:disabled) {
    background: linear-gradient(135deg, #28a745 0%, #218838 100%);
    border-left: 4px solid #1e7e34;
    box-shadow: 0 4px 8px rgba(40, 167, 69, 0.3);
  }
  
  /* 移动端禁用按钮样式 */
  .pick-btn:disabled, .complete-btn:disabled, .confirm-btn:disabled {
    background: #f8f9fa;
    color: #adb5bd;
    border-left: 4px solid #e9ecef;
    box-shadow: none;
    opacity: 0.6;
  }
  
  /* 移动端已绑定容器的按钮特殊样式 */
  .complete-btn.container-bound {
    background: linear-gradient(135deg, #17a2b8 0%, #138496 100%) !important;
    color: white !important;
    border-left: 4px solid #117a8b !important;
    opacity: 1 !important;
    cursor: not-allowed;
  }
  
  .submit-btn {
    width: 100%;
    padding: 1.25rem;
    font-size: 1.1rem;
    min-height: 56px;
    border-radius: 12px;
    background: #28a745 !important;
  }
  
  /* 移动端容器选择模态框优化 */
  .container-modal-content {
    max-width: 95%;
    padding: 1.5rem;
    max-height: 85vh;
  }
  
  .container-modal-content h3 {
    font-size: 1.2rem;
    margin-bottom: 0.75rem;
  }
  
  .container-modal-content p {
    font-size: 0.9rem;
    margin-bottom: 1rem;
  }
  
  .container-list {
    max-height: 250px;
    margin-bottom: 1.5rem;
  }
  
  .container-item {
    padding: 0.75rem;
    flex-direction: column;
    align-items: flex-start;
    gap: 0.25rem;
  }
  
  .container-code {
    font-size: 1rem;
  }
  
  .container-status {
    font-size: 0.8rem;
  }
  
  /* 优化订单信息在移动端的显示 */
  .product-name {
    font-size: 1.1rem;
    line-height: 1.4;
    margin-bottom: 0.5rem;
  }
  
  .order-meta {
    grid-template-columns: 1fr;
    gap: 0.25rem;
    margin-bottom: 0.5rem;
  }
  
  .meta-item {
    font-size: 0.8rem;
  }
  
  .meta-label {
    min-width: 70px;
    font-size: 0.75rem;
  }
  
  .meta-value {
    font-size: 0.8rem;
  }
  
  .meta-value.status {
    font-size: 0.7rem;
    padding: 0.15rem 0.4rem;
  }

  /* 移动端待确认状态样式加强 */
  .meta-value.status.status-pending-confirm {
    background: #cce5ff;
    color: #0056b3;
    border: 1px solid #007bff;
    font-weight: 600;
    animation: pulse-pending 2s infinite;
  }

  @keyframes pulse-pending {
    0% { box-shadow: 0 0 0 0 rgba(0, 123, 255, 0.4); }
    70% { box-shadow: 0 0 0 4px rgba(0, 123, 255, 0); }
    100% { box-shadow: 0 0 0 0 rgba(0, 123, 255, 0); }
  }
  
  .quantity-info {
    display: flex;
    gap: 1rem;
    margin-bottom: 0.5rem;
  }
  
  .quantity-info span {
    background: #f8f9fa;
    padding: 0.25rem 0.5rem;
    border-radius: 4px;
    font-weight: 500;
    color: #495057;
  }
  
  /* 拣货详情页面移动端优化 */
  .picking-detail {
    min-height: auto;
  }
  
  .product-info, .location-info, .pick-form {
    margin: 0.25rem 0.5rem;
    padding: 0.75rem;
  }
  
  .info-item, .location-item {
    margin-bottom: 0.25rem;
    font-size: 0.85rem;
  }
  
  .info-item label, .location-item label {
    width: 80px;
    font-size: 0.8rem;
  }
  
  .info-item span, .location-item span {
    font-size: 0.8rem;
  }
  
  .form-group {
    margin-bottom: 0.75rem;
  }
  
  .form-group label {
    font-size: 0.9rem;
    margin-bottom: 0.25rem;
  }
  
  .form-group input {
    padding: 0.6rem;
    font-size: 0.9rem;
  }
  
  .quantity-info {
    margin-top: 0.25rem;
    font-size: 0.8rem;
  }
  
  .error-message {
    margin-top: 0.25rem;
    padding: 0.4rem;
    font-size: 0.8rem;
  }
  
  /* 确保选择库位组件紧凑显示 */
  .location-select {
    padding: 0.6rem;
    font-size: 0.9rem;
  }
  
  .single-location, .no-location, .loading-location {
    padding: 0.6rem;
    font-size: 0.85rem;
  }
  
  /* 优化页面header */
  .header {
    padding: 0.75rem 1rem;
  }
  
  .header h2 {
    font-size: 1.1rem;
  }
  
  .back-btn {
    padding: 0.4rem 0.8rem;
    font-size: 0.85rem;
  }
}
</style>